umangchaudhry commited on
Commit
c5afa27
Β·
verified Β·
1 Parent(s): 8ddcfdd

collapsible side bar

Browse files
Files changed (1) hide show
  1. app.py +108 -51
app.py CHANGED
@@ -47,33 +47,87 @@ def initialize_agent():
47
  return False
48
 
49
 
50
- def chat(message, history, session_id):
51
  """
52
- Handle chat interaction
53
 
54
  Args:
55
  message: User's message
56
- history: Chat history (list of [user_msg, bot_msg] pairs)
57
  session_id: Unique session identifier for conversation memory
 
 
 
58
  """
59
  if initialization_error:
60
- return initialization_error
 
61
 
62
  if not agent:
63
- return "⚠️ Agent not initialized. Please refresh the page."
 
64
 
65
  if not message.strip():
66
- return ""
67
 
68
  try:
69
- # Use session_id as thread_id for conversation memory
70
- answer = agent.query(message, thread_id=session_id)
71
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
  except Exception as e:
74
  error_msg = f"❌ Error processing query: {str(e)}"
75
- print(f"Error details: {e}") # Log to console
76
- return error_msg
 
 
77
 
78
 
79
  def create_new_session():
@@ -179,44 +233,44 @@ with gr.Blocks(title="Survey Analysis Agent", theme=gr.themes.Soft()) as demo:
179
  label="πŸ’‘ Example Questions"
180
  )
181
 
182
- # Sidebar with info
183
  with gr.Column(scale=1):
184
- gr.Markdown("## πŸ“‹ Available Data")
185
- survey_info = gr.Markdown(
186
- value=get_available_surveys() if init_success else "Agent not initialized",
187
- )
188
-
189
- refresh_info = gr.Button("πŸ”„ Refresh", size="sm")
190
-
191
- gr.Markdown("""
192
- ## 🎯 What I Can Do
193
-
194
- **πŸ“ Questionnaires**
195
- - Question text & options
196
- - Topics and themes
197
- - Skip logic & sampling
198
- - Question sequencing
199
-
200
- **πŸ“Š Response Data**
201
- - Overall percentages
202
- - Demographic breakdowns
203
- - Cross-tabulations
204
- - Time comparisons
205
-
206
- ## πŸ’‘ Tips
207
 
208
- - Specify time periods when relevant
209
- - Ask follow-up questions for more detail
210
- - I maintain conversation context
211
- - Request comparisons across time periods
 
 
 
 
 
 
 
 
 
 
212
 
213
- ## πŸ”§ Current Status
 
 
 
 
 
 
214
 
215
- βœ… Questionnaire data
216
- βœ… Toplines (response %)
217
- βœ… Crosstabs (demographics)
218
- ⏳ SQL queries (coming soon)
219
- """)
 
 
220
 
221
  # Footer
222
  gr.Markdown("""
@@ -227,20 +281,23 @@ with gr.Blocks(title="Survey Analysis Agent", theme=gr.themes.Soft()) as demo:
227
 
228
  # Event handlers
229
  def respond(message, chat_history, session_id):
230
- """Handle message and update chat history"""
231
  if not message.strip():
232
  return chat_history, ""
233
 
234
  # Add user message
235
  chat_history.append({"role": "user", "content": message})
236
 
237
- # Get bot response
238
- bot_message = chat(message, chat_history, session_id)
239
 
240
- # Add bot message
241
- chat_history.append({"role": "assistant", "content": bot_message})
 
 
242
 
243
- return chat_history, ""
 
244
 
245
  def clear_chat():
246
  """Clear chat and create new session"""
 
47
  return False
48
 
49
 
50
+ def chat_with_streaming(message, history, session_id):
51
  """
52
+ Stream response for better UX
53
 
54
  Args:
55
  message: User's message
56
+ history: Chat history (not used in streaming)
57
  session_id: Unique session identifier for conversation memory
58
+
59
+ Yields:
60
+ Partial responses as they become available
61
  """
62
  if initialization_error:
63
+ yield initialization_error
64
+ return
65
 
66
  if not agent:
67
+ yield "⚠️ Agent not initialized. Please refresh the page."
68
+ return
69
 
70
  if not message.strip():
71
+ return
72
 
73
  try:
74
+ # Show that we're processing
75
+ yield "πŸ€” Analyzing your question..."
76
+
77
+ # Debug: Check if stream_query exists
78
+ if not hasattr(agent, 'stream_query'):
79
+ print("⚠️ WARNING: agent.stream_query() not found, falling back to regular query")
80
+ yield agent.query(message, thread_id=session_id)
81
+ return
82
+
83
+ # Stream events from agent
84
+ has_answer = False
85
+ event_count = 0
86
+
87
+ for event in agent.stream_query(message, thread_id=session_id):
88
+ event_count += 1
89
+ print(f"πŸ“‘ Stream event {event_count}: {list(event.keys()) if event else 'None'}")
90
+
91
+ if not event:
92
+ continue
93
+
94
+ # Get current node
95
+ node = list(event.keys())[0]
96
+ print(f" Processing node: {node}")
97
+
98
+ # Show progress based on which node is executing
99
+ if node == "generate_research_brief":
100
+ yield "πŸ“‹ Planning research strategy..."
101
+ elif node == "execute_stage":
102
+ yield "πŸ“Š Retrieving data from surveys..."
103
+ elif node == "extract_stage_context":
104
+ yield "πŸ”— Processing retrieved data..."
105
+ elif node == "verify_results":
106
+ yield "βœ“ Verifying data completeness..."
107
+ elif node == "synthesize_response":
108
+ yield "✍️ Synthesizing answer..."
109
+ # Get final answer
110
+ state = event[node]
111
+ final_answer = state.get("final_answer")
112
+ if final_answer:
113
+ print(f" Got final answer ({len(final_answer)} chars)")
114
+ yield final_answer
115
+ has_answer = True
116
+ return
117
+
118
+ print(f"πŸ“‘ Stream complete. Total events: {event_count}, Has answer: {has_answer}")
119
+
120
+ # Fallback if streaming didn't provide answer
121
+ if not has_answer:
122
+ print("⚠️ No answer from streaming, using regular query")
123
+ yield agent.query(message, thread_id=session_id)
124
 
125
  except Exception as e:
126
  error_msg = f"❌ Error processing query: {str(e)}"
127
+ print(f"Error details: {e}")
128
+ import traceback
129
+ traceback.print_exc()
130
+ yield error_msg
131
 
132
 
133
  def create_new_session():
 
233
  label="πŸ’‘ Example Questions"
234
  )
235
 
236
+ # Collapsible sidebar with info
237
  with gr.Column(scale=1):
238
+ with gr.Accordion("πŸ“‹ Available Data", open=False):
239
+ survey_info = gr.Markdown(
240
+ value=get_available_surveys() if init_success else "Agent not initialized",
241
+ )
242
+ refresh_info = gr.Button("πŸ”„ Refresh", size="sm")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
 
244
+ with gr.Accordion("🎯 What I Can Do", open=False):
245
+ gr.Markdown("""
246
+ **πŸ“ Questionnaires**
247
+ - Question text & options
248
+ - Topics and themes
249
+ - Skip logic & sampling
250
+ - Question sequencing
251
+
252
+ **πŸ“Š Response Data**
253
+ - Overall percentages
254
+ - Demographic breakdowns
255
+ - Cross-tabulations
256
+ - Time comparisons
257
+ """)
258
 
259
+ with gr.Accordion("πŸ’‘ Tips", open=False):
260
+ gr.Markdown("""
261
+ - Specify time periods when relevant
262
+ - Ask follow-up questions for more detail
263
+ - I maintain conversation context
264
+ - Request comparisons across time periods
265
+ """)
266
 
267
+ with gr.Accordion("πŸ”§ Current Status", open=False):
268
+ gr.Markdown("""
269
+ βœ… Questionnaire data
270
+ βœ… Toplines (response %)
271
+ βœ… Crosstabs (demographics)
272
+ ⏳ SQL queries (coming soon)
273
+ """)
274
 
275
  # Footer
276
  gr.Markdown("""
 
281
 
282
  # Event handlers
283
  def respond(message, chat_history, session_id):
284
+ """Handle message with streaming updates"""
285
  if not message.strip():
286
  return chat_history, ""
287
 
288
  # Add user message
289
  chat_history.append({"role": "user", "content": message})
290
 
291
+ # Add placeholder for assistant response
292
+ chat_history.append({"role": "assistant", "content": ""})
293
 
294
+ # Stream updates
295
+ for partial_response in chat_with_streaming(message, chat_history, session_id):
296
+ chat_history[-1]["content"] = partial_response
297
+ yield chat_history, ""
298
 
299
+ # Final return
300
+ yield chat_history, ""
301
 
302
  def clear_chat():
303
  """Clear chat and create new session"""