-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact_agent_dashboard.py
More file actions
426 lines (364 loc) · 15.2 KB
/
Copy pathreact_agent_dashboard.py
File metadata and controls
426 lines (364 loc) · 15.2 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
from typing import Union
import streamlit as st
import json
import pandas as pd
from amber_dashboard import build_reaction_dashboard
from structured_agent import (
StructuredAgent,
InsightResponse,
MessageItem,
TableItem,
ChartItem,
get_all_answers,
get_presentation_count,
get_response_count,
get_slide_count,
initialize_agent,
stream_agent_response
)
def pretty_print(step):
print(f'\n' + '-' * 100 + '\n')
def print_dict(d, indent=0):
pad = ' ' * indent
for k, v in d.items():
if isinstance(v, dict):
print(f'{pad}{k} (dict):')
print_dict(v, indent + 1)
elif isinstance(v, list):
print(f'{pad}{k} (list):')
for i, elem in enumerate(v):
elem_type = type(elem).__name__
if isinstance(elem, dict):
print(f'{pad} [{i}] (dict):')
print_dict(elem, indent + 2)
elif isinstance(elem, list):
print(f'{pad} [{i}] (list): {elem}')
else:
print(f'{pad} [{i}] ({elem_type}): {elem}')
else:
val_type = type(v).__name__
print(f'{pad}{k} ({val_type}): {v}')
if isinstance(step, list):
for i, item in enumerate(step):
item_type = type(item).__name__
if isinstance(item, dict):
print(f'Item {i} (dict):')
print_dict(item, 1)
elif isinstance(item, list):
print(f'Item {i} (list):')
for idx, val in enumerate(item):
val_type = type(val).__name__
print(f' [{idx}] ({val_type}): {val}')
else:
print(f'Item {i} ({item_type}): {item}')
elif isinstance(step, dict):
print_dict(step)
else:
print(f'({type(step).__name__}): {step}')
print(f'-' * 100 + '\n')
def stream_agent_response_ui(agent: StructuredAgent, prompt):
"""Stream the agent response with UI updates"""
# Create a placeholder for streaming output
message_placeholder = st.empty()
tool_executions = []
info_placeholder = st.empty()
try:
for step in agent.stream_query(prompt):
print(f'UI STEP')
print(f'\n' + '-' * 100 + '\n')
print(f'\nUI Step: {step}')
if step and step.get("messages"):
pretty_print(step)
# print(step)
last_message = step["messages"][-1]
if hasattr(last_message, 'content') and last_message.content:
# Update the streaming display
if last_message.type == "ai":
# Display tool executions if any
if tool_executions:
for tool_info in tool_executions:
info_placeholder.info(f"🔧 Executed: {tool_info}")
# st.info(f"🔧 Executed: {tool_info}")
# Use helper function to display response
message_placeholder.empty()
with message_placeholder.container():
try:
markdown_content = last_message.content[0]['text']
except Exception as e:
markdown_content = 'Giving my conclusion...'
st.markdown(markdown_content)
elif last_message.type == "tool":
# Track tool execution
tool_name = getattr(last_message, 'name', 'Unknown Tool')
tool_executions.append(f"{tool_name}")
# st.info(f"🔧 Executing: {tool_name}...")
info_placeholder.info(f"🔧 Executing: {tool_name}...")
print(f'\n\nFinished streaming agent response\n')
print(f'{type(agent.get_structured_output())}: {agent.get_structured_output()}')
return agent.get_structured_output()
except Exception as e:
print(f'Error executing agent: {str(e)}')
import traceback
traceback.print_exc()
st.error(f"Error executing agent: {str(e)}")
return agent.get_structured_output()
def display_visualization(item: Union[TableItem, ChartItem]):
if item.type == "table":
display_table(item)
elif item.type == "chart":
display_chart(item)
def display_table(item):
if item.title and item.title.strip():
st.markdown(f"📊 **{item.title}**")
df = pd.DataFrame(item.data)
st.dataframe(df)
import altair as alt
def pie_chart_from_df(df, title=None):
category_col = df.columns[0]
value_col = df.columns[1]
chart = alt.Chart(df).mark_arc().encode(
theta=alt.Theta(field=value_col, type="quantitative"),
color=alt.Color(field=category_col, type="nominal"),
tooltip=[
alt.Tooltip(f"{category_col}:N", title=category_col),
alt.Tooltip(f"{value_col}:Q", title=value_col)
]
)
if title:
chart = chart.properties(title=title)
return chart
def display_chart(item):
if item.title and item.title.strip():
st.markdown(f"📈 **{item.title}**")
df = pd.DataFrame(item.data)
if item.chart_type == "bar":
st.bar_chart(df, x=df.columns[0], y=df.columns[1])
elif item.chart_type == "line":
st.line_chart(df, x=df.columns[0], y=df.columns[1])
elif item.chart_type == "area":
st.area_chart(df, x=df.columns[0], y=df.columns[1])
elif item.chart_type == "pie":
try:
chart = pie_chart_from_df(df, item.title)
st.altair_chart(chart, use_container_width=True)
except Exception as e:
import traceback
traceback.print_exc()
st.dataframe(df)
st.info(f"Chart type '{item.chart_type}' displayed as table")
else:
# Default to dataframe if chart type not supported
st.dataframe(df)
st.info(f"Chart type '{item.chart_type}' displayed as table")
def display_structured_response(response_content):
"""Helper function to display structured responses consistently"""
if isinstance(response_content, InsightResponse):
print(f'-'*100 + '\n')
print(f'Instance of Insight response_content: {response_content}')
# Handle structured response object
for item in response_content.items:
if item.type == "message":
st.markdown(f"💬{item.content}")
elif item.type == "table":
display_table(item)
elif item.type == "chart":
display_chart(item)
return True
elif isinstance(response_content, str):
print(f'-'*100 + '\n')
print(f'Instance of legacy JSON format')
print(f'{response_content}')
print(f'-'*100 + '\n')
# Handle legacy JSON format for backward compatibility
try:
if "```json" in response_content:
# extract the inner text between ```json and ```
message_content = response_content.split('```json')[1].split('```')[0]
message_content = json.loads(message_content.replace("\n", ""))
if "rows" in message_content and "cols" in message_content:
if "message" in message_content:
st.markdown(f"💬 **Analysis:** {message_content['message']}")
df = pd.DataFrame(message_content['rows'], columns=message_content['cols'])
st.dataframe(df)
else:
st.markdown(response_content)
return True
except Exception as e:
st.info(f'Cannot parse JSON content: {str(e)}')
st.markdown(response_content)
return True
# Fallback for plain text
st.markdown(response_content)
return False
def create_configuration():
if st.button("Clear Chat History"):
st.session_state.messages = []
st.rerun()
with st.spinner("Speed up query..."):
print(f'Preload data for {st.session_state.current_user_id}')
get_all_answers(st.session_state.current_user_id)
print(f'DONE Preload data for {st.session_state.current_user_id}')
def st_process_user_prompt(agent, prompt, stream_response_ui_func=None):
st.session_state.messages.append({"role": "user", "content": prompt})
if stream_response_ui_func is None:
stream_response_ui_func = stream_agent_response_ui
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
with st.spinner("..."):
try:
response = stream_response_ui_func(agent, prompt)
if response:
st.session_state.messages.append({"role": "assistant", "content": response})
else:
error_msg = "Sorry, I encountered an error processing your request."
st.error(error_msg)
st.session_state.messages.append({"role": "assistant", "content": error_msg})
except Exception as e:
error_msg = str(e)
if "max_tokens" in error_msg.lower() or "truncated" in error_msg.lower():
st.warning("⚠️ The response was truncated. Try asking a more specific question or break your request into smaller parts.")
fallback_response = InsightResponse(items=[
MessageItem(
type="message",
content="The response was truncated due to length limits. Please try asking a more specific question."
)
])
st.session_state.messages.append({"role": "assistant", "content": fallback_response})
else:
st.error(f"Error: {error_msg}")
st.session_state.messages.append({"role": "assistant", "content": f"Error: {error_msg}"})
st.rerun()
def create_agent_dashboard(username, user_id):
# Page configuration
st.set_page_config(
page_title="AI Data Assistant",
page_icon="🤖",
layout="centered"
)
# Initialize session state
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'agent_executor' not in st.session_state:
st.session_state.agent_executor = None
if 'current_user_id' not in st.session_state:
st.session_state.current_user_id = user_id
if 'agent' not in st.session_state:
st.session_state.agent = StructuredAgent(user_id=st.session_state.current_user_id)
# Main UI
st.subheader(f"Hi {username.capitalize()}")
st.markdown("Welcome to Data Chat - your assistant for session analytics.")
if 'query' not in st.session_state:
st.markdown("Here are some quick insights from all your sessions:")
col1, col2, col3 = st.columns(3)
with col1:
with st.container(border=True, height=150):
presentation_count = get_presentation_count(st.session_state.current_user_id)
st.metric('Total sessions', presentation_count)
with col2:
with st.container(border=True, height=150):
response_count = get_response_count(st.session_state.current_user_id)
st.metric('Responses Collected', response_count)
with col3:
with st.container(border=True, height=150):
slide_count = get_slide_count(st.session_state.current_user_id)
st.metric('Slides Created', slide_count)
for message in st.session_state.messages:
with st.chat_message(message["role"]):
if message["role"] == "assistant":
display_structured_response(message['content'])
else:
st.markdown(message['content'])
st.markdown("""
Want deeper insight? Ask me anything about your presentations, or click a suggestion
""")
example_queries = [
"Show engagement & completion rates",
"Who engaged the most?",
"Which questions were most commonly wrong?",
"Compare sessions over time"
]
with st.container(horizontal=True):
for query in example_queries:
if st.button(f"{query}", key=f"example_{hash(query)}", icon=":material/search_insights:"):
st.session_state.query = query
st.rerun() # Explicit rerun after setting the query
if 'query' in st.session_state and st.session_state.query:
query_to_process = st.session_state.query
st.session_state.query = None # Clear it BEFORE processing
st_process_user_prompt(st.session_state.agent, query_to_process)
if prompt := st.chat_input("Ask about your sessions, slides, or audience insights..."):
st_process_user_prompt(st.session_state.agent, prompt)
# # Sidebar for configuration
# with st.sidebar:
# create_configuration()
# def query_builder_page():
# st.title("Query builder")
# pg = st.navigation(["query_builder_dashboard.py", query_builder_page])
# pg.run()
user_map = {
'tara': 3146502,
'april': 2992027,
'kiotViet': 259137,
'cheryl': 1918789,
'duke': 1472007,
'don': 1851905,
'amber': 3802280,
}
def agent_dashboard_page():
query_params = st.query_params
user = query_params.get("user", "duke") # Default to "home"
if user in user_map:
create_agent_dashboard(user, user_map.get(user))
else:
st.write(f'Not supported user: {user}')
def reaction_dashboard_page():
query_params = st.query_params
user = query_params.get("user", "duke") # Default to "home"
if user in user_map:
st.set_page_config(layout="wide")
build_reaction_dashboard(user_map.get(user))
else:
st.write(f'Not supported user: {user}')
if __name__ == "__main__":
st.logo('https://ahaslides.com/wp-content/uploads/2025/05/logo-full.png')
# This CSS will definitely hide the Deploy button
st.markdown("""
<style>
/* Hide the Deploy button and menu */
[data-testid="stToolbar"] {
display: none !important;
}
/* Hide header completely */
header[data-testid="stHeader"] {
display: none !important;
}
/* Backup selectors for Deploy button */
button[title*="Deploy"],
button[title*="Rerun"],
div[data-testid="stDecoration"] {
display: none !important;
}
/* Remove any remaining toolbar elements */
.stApp > header {
display: none !important;
}
</style>
""", unsafe_allow_html=True)
st.set_page_config(
page_title="Your App",
page_icon="🚀",
menu_items={
'Get Help': None,
'Report a bug': None,
'About': None
}
)
# agent_dashboard_page()
pg = st.navigation([
st.Page(agent_dashboard_page, title="Agent"),
st.Page('metrics_dashboard.py', title="Presentation metrics"),
st.Page(reaction_dashboard_page, title="Reaction Metrics"),
st.Page("query_builder_dashboard.py", title="Build your own report"),
])
pg.run()