0
# Advanced Features
1
2
Chat interfaces, app fragments, modal dialogs, and database connections for sophisticated applications. These features enable building complex, interactive applications with modern UI patterns.
3
4
## Capabilities
5
6
### Chat Interface
7
8
Build conversational interfaces and chatbots with built-in message containers and input handling.
9
10
```python { .api }
11
def chat_message(name, *, avatar=None):
12
"""
13
Create chat message container with sender name and optional avatar.
14
15
Args:
16
name (str): Name of the message sender
17
avatar (str, optional): Avatar image URL, emoji, or user type ("user", "assistant")
18
19
Returns:
20
DeltaGenerator: Chat message container context manager
21
"""
22
23
def chat_input(placeholder=None, key=None, max_chars=None, on_submit=None, args=None, kwargs=None, *, disabled=False):
24
"""
25
Display chat input widget for user message entry.
26
27
Args:
28
placeholder (str, optional): Placeholder text when empty
29
key (str, optional): Unique widget key for state management
30
max_chars (int, optional): Maximum number of characters allowed
31
on_submit (callable, optional): Callback function when message is submitted
32
args (tuple, optional): Arguments for on_submit callback
33
kwargs (dict, optional): Keyword arguments for on_submit callback
34
disabled (bool): Whether input is disabled
35
36
Returns:
37
str: Submitted message text or empty string if no submission
38
"""
39
```
40
41
Example usage:
42
```python
43
# Initialize chat history in session state
44
if "messages" not in st.session_state:
45
st.session_state.messages = []
46
47
# Display chat history
48
for message in st.session_state.messages:
49
with st.chat_message(message["role"], avatar=message.get("avatar")):
50
st.write(message["content"])
51
52
# Chat input
53
user_input = st.chat_input("Type your message here...")
54
55
if user_input:
56
# Add user message to history
57
st.session_state.messages.append({
58
"role": "user",
59
"content": user_input,
60
"avatar": "π§βπ»"
61
})
62
63
# Display user message
64
with st.chat_message("user", avatar="π§βπ»"):
65
st.write(user_input)
66
67
# Generate and display assistant response
68
response = generate_response(user_input) # Your AI logic here
69
70
st.session_state.messages.append({
71
"role": "assistant",
72
"content": response,
73
"avatar": "π€"
74
})
75
76
with st.chat_message("assistant", avatar="π€"):
77
st.write(response)
78
```
79
80
### App Fragments
81
82
Create reusable, independently updating app components for better performance and modularity.
83
84
```python { .api }
85
def fragment(func):
86
"""
87
Decorator to create app fragment that can update independently.
88
89
Args:
90
func (callable): Function to convert to fragment
91
92
Returns:
93
callable: Fragment function that can be called with arguments
94
"""
95
```
96
97
Example usage:
98
```python
99
@st.fragment
100
def live_metrics_fragment():
101
"""Fragment that updates metrics independently."""
102
col1, col2, col3 = st.columns(3)
103
104
with col1:
105
cpu_usage = get_cpu_usage() # Real-time data
106
st.metric("CPU Usage", f"{cpu_usage}%")
107
108
with col2:
109
memory_usage = get_memory_usage()
110
st.metric("Memory", f"{memory_usage}%")
111
112
with col3:
113
active_users = get_active_users()
114
st.metric("Active Users", active_users)
115
116
# Auto-refresh every 5 seconds
117
time.sleep(5)
118
st.rerun()
119
120
@st.fragment
121
def data_table_fragment(data, filters):
122
"""Fragment for data table that updates based on filters."""
123
filtered_data = apply_filters(data, filters)
124
st.dataframe(filtered_data)
125
126
if st.button("Export Data"):
127
export_data(filtered_data)
128
st.success("Data exported!")
129
130
# Main app
131
st.title("Dashboard")
132
133
# Independent fragments
134
live_metrics_fragment() # Updates independently
135
136
# Fragment with parameters
137
data = load_data()
138
current_filters = st.selectbox("Filter by", ["All", "Active", "Inactive"])
139
data_table_fragment(data, current_filters)
140
```
141
142
### Modal Dialogs
143
144
Create modal dialog overlays for focused user interactions and confirmations.
145
146
```python { .api }
147
def dialog(title, *, width="small"):
148
"""
149
Create modal dialog container that overlays the main content.
150
151
Args:
152
title (str): Dialog title displayed in header
153
width (str): Dialog width ("small", "medium", "large")
154
155
Returns:
156
DeltaGenerator: Dialog container context manager
157
"""
158
```
159
160
Example usage:
161
```python
162
# Dialog trigger
163
if st.button("Open Settings"):
164
st.session_state.show_settings = True
165
166
# Dialog content
167
if st.session_state.get("show_settings", False):
168
@st.dialog("Application Settings")
169
def settings_dialog():
170
st.write("Configure your application settings")
171
172
# Settings form
173
theme = st.selectbox("Theme", ["Light", "Dark"])
174
notifications = st.checkbox("Enable notifications")
175
auto_save = st.checkbox("Auto-save changes")
176
177
col1, col2 = st.columns(2)
178
with col1:
179
if st.button("Save", type="primary"):
180
save_settings(theme, notifications, auto_save)
181
st.session_state.show_settings = False
182
st.rerun()
183
184
with col2:
185
if st.button("Cancel"):
186
st.session_state.show_settings = False
187
st.rerun()
188
189
settings_dialog()
190
191
# Confirmation dialog
192
if st.button("Delete Item"):
193
st.session_state.confirm_delete = True
194
195
if st.session_state.get("confirm_delete", False):
196
@st.dialog("Confirm Deletion", width="medium")
197
def confirm_dialog():
198
st.warning("Are you sure you want to delete this item?")
199
st.write("This action cannot be undone.")
200
201
col1, col2 = st.columns(2)
202
with col1:
203
if st.button("Delete", type="primary"):
204
delete_item()
205
st.session_state.confirm_delete = False
206
st.success("Item deleted!")
207
st.rerun()
208
209
with col2:
210
if st.button("Cancel"):
211
st.session_state.confirm_delete = False
212
st.rerun()
213
214
confirm_dialog()
215
```
216
217
### Database Connections
218
219
Streamlined database connectivity with built-in connection management and query capabilities.
220
221
```python { .api }
222
def connection(name, type=None, **kwargs):
223
"""
224
Create or retrieve database connection with automatic management.
225
226
Args:
227
name (str): Connection name for reuse
228
type (str, optional): Connection type ("sql", "snowflake", etc.)
229
**kwargs: Connection-specific parameters
230
231
Returns:
232
Connection: Database connection object with query methods
233
"""
234
```
235
236
Example usage:
237
```python
238
# SQL database connection
239
conn = st.connection("my_database", type="sql", url="sqlite:///data.db")
240
241
# Execute query
242
@st.cache_data
243
def load_data():
244
return conn.query("SELECT * FROM users WHERE active = 1")
245
246
data = load_data()
247
st.dataframe(data)
248
249
# Snowflake connection
250
snow_conn = st.connection(
251
"snowflake_db",
252
type="snowflake",
253
account=st.secrets["snowflake"]["account"],
254
user=st.secrets["snowflake"]["user"],
255
password=st.secrets["snowflake"]["password"],
256
database="ANALYTICS",
257
schema="PUBLIC"
258
)
259
260
# Query with parameters
261
@st.cache_data
262
def get_sales_data(start_date, end_date):
263
query = """
264
SELECT date, product, sales
265
FROM sales_data
266
WHERE date BETWEEN %s AND %s
267
ORDER BY date
268
"""
269
return snow_conn.query(query, params=(start_date, end_date))
270
271
# Custom connection parameters
272
postgres_conn = st.connection(
273
"postgres",
274
type="sql",
275
url="postgresql://user:password@localhost/mydb",
276
engine_kwargs={
277
"pool_size": 10,
278
"pool_recycle": 3600
279
}
280
)
281
```
282
283
### Advanced Application Patterns
284
285
#### Real-time Chat Application
286
287
```python
288
import time
289
from datetime import datetime
290
291
# Initialize chat application
292
if "chat_history" not in st.session_state:
293
st.session_state.chat_history = []
294
st.session_state.user_name = ""
295
296
# User setup
297
if not st.session_state.user_name:
298
st.session_state.user_name = st.text_input("Enter your name to start chatting:")
299
if not st.session_state.user_name:
300
st.stop()
301
302
st.title(f"π¬ Chat - Welcome {st.session_state.user_name}!")
303
304
# Chat history fragment (updates independently)
305
@st.fragment
306
def chat_history_fragment():
307
"""Display chat messages with real-time updates."""
308
chat_container = st.container(height=400, border=True)
309
310
with chat_container:
311
for message in st.session_state.chat_history:
312
timestamp = message.get("timestamp", "")
313
with st.chat_message(message["role"], avatar=message["avatar"]):
314
st.write(f"**{message['name']}** - {timestamp}")
315
st.write(message["content"])
316
317
# Display chat history
318
chat_history_fragment()
319
320
# Message input
321
message = st.chat_input("Type your message...")
322
323
if message:
324
# Add message to history
325
new_message = {
326
"role": "user",
327
"name": st.session_state.user_name,
328
"content": message,
329
"avatar": "π§βπ»",
330
"timestamp": datetime.now().strftime("%H:%M:%S")
331
}
332
333
st.session_state.chat_history.append(new_message)
334
335
# Simulate bot response
336
if message.lower().startswith("!bot"):
337
bot_response = generate_bot_response(message[5:]) # Remove "!bot "
338
bot_message = {
339
"role": "assistant",
340
"name": "ChatBot",
341
"content": bot_response,
342
"avatar": "π€",
343
"timestamp": datetime.now().strftime("%H:%M:%S")
344
}
345
st.session_state.chat_history.append(bot_message)
346
347
st.rerun()
348
```
349
350
#### Interactive Dashboard with Fragments
351
352
```python
353
@st.fragment
354
def metric_cards_fragment():
355
"""Independent metrics that update frequently."""
356
col1, col2, col3, col4 = st.columns(4)
357
358
with col1:
359
revenue = get_current_revenue()
360
st.metric("Revenue", f"${revenue:,.2f}", delta="12.5%")
361
362
with col2:
363
users = get_active_users()
364
st.metric("Active Users", f"{users:,}", delta="5.2%")
365
366
with col3:
367
conversion = get_conversion_rate()
368
st.metric("Conversion Rate", f"{conversion:.1f}%", delta="-1.2%")
369
370
with col4:
371
satisfaction = get_satisfaction_score()
372
st.metric("Satisfaction", f"{satisfaction}/5", delta="0.3")
373
374
@st.fragment
375
def interactive_chart_fragment(data, chart_type, filters):
376
"""Chart fragment that updates based on user selections."""
377
filtered_data = apply_dashboard_filters(data, filters)
378
379
if chart_type == "Line":
380
st.line_chart(filtered_data)
381
elif chart_type == "Bar":
382
st.bar_chart(filtered_data)
383
elif chart_type == "Area":
384
st.area_chart(filtered_data)
385
386
# Main dashboard
387
st.title("π Real-time Dashboard")
388
389
# Independent metrics (updates every few seconds)
390
metric_cards_fragment()
391
392
# Interactive controls
393
col1, col2 = st.columns([1, 3])
394
395
with col1:
396
chart_type = st.selectbox("Chart Type", ["Line", "Bar", "Area"])
397
date_range = st.date_input("Date Range", value=[datetime.now() - timedelta(days=30), datetime.now()])
398
categories = st.multiselect("Categories", ["Sales", "Marketing", "Support"])
399
400
with col2:
401
# Load data
402
dashboard_data = load_dashboard_data()
403
filters = {
404
"date_range": date_range,
405
"categories": categories
406
}
407
408
# Interactive chart fragment
409
interactive_chart_fragment(dashboard_data, chart_type, filters)
410
```
411
412
#### Modal-Based Workflows
413
414
```python
415
# Workflow state management
416
workflow_states = {
417
"create_project": False,
418
"edit_item": None,
419
"confirm_action": None
420
}
421
422
for state_key in workflow_states:
423
if state_key not in st.session_state:
424
st.session_state[state_key] = workflow_states[state_key]
425
426
# Main interface
427
st.title("Project Management")
428
429
# Action buttons
430
col1, col2, col3 = st.columns(3)
431
432
with col1:
433
if st.button("β New Project", type="primary"):
434
st.session_state.create_project = True
435
436
with col2:
437
if st.button("π Edit Selected"):
438
if selected_item := get_selected_item():
439
st.session_state.edit_item = selected_item
440
441
with col3:
442
if st.button("ποΈ Delete Selected"):
443
if selected_item := get_selected_item():
444
st.session_state.confirm_action = f"delete_{selected_item['id']}"
445
446
# Create Project Dialog
447
if st.session_state.create_project:
448
@st.dialog("Create New Project", width="large")
449
def create_project_dialog():
450
st.write("Enter project details:")
451
452
project_name = st.text_input("Project Name*")
453
description = st.text_area("Description")
454
455
col1, col2 = st.columns(2)
456
with col1:
457
start_date = st.date_input("Start Date")
458
priority = st.selectbox("Priority", ["Low", "Medium", "High"])
459
460
with col2:
461
due_date = st.date_input("Due Date")
462
assignee = st.selectbox("Assignee", get_team_members())
463
464
# Dialog actions
465
col1, col2 = st.columns(2)
466
with col1:
467
if st.button("Create Project", type="primary", disabled=not project_name):
468
create_new_project({
469
"name": project_name,
470
"description": description,
471
"start_date": start_date,
472
"due_date": due_date,
473
"priority": priority,
474
"assignee": assignee
475
})
476
st.session_state.create_project = False
477
st.success("Project created!")
478
st.rerun()
479
480
with col2:
481
if st.button("Cancel"):
482
st.session_state.create_project = False
483
st.rerun()
484
485
create_project_dialog()
486
487
# Edit Item Dialog
488
if st.session_state.edit_item:
489
@st.dialog("Edit Item", width="medium")
490
def edit_item_dialog():
491
item = st.session_state.edit_item
492
st.write(f"Editing: {item['name']}")
493
494
# Editable fields
495
new_name = st.text_input("Name", value=item['name'])
496
new_status = st.selectbox("Status", ["Active", "Completed", "On Hold"],
497
index=["Active", "Completed", "On Hold"].index(item['status']))
498
499
# Save/Cancel actions
500
col1, col2 = st.columns(2)
501
with col1:
502
if st.button("Save Changes", type="primary"):
503
update_item(item['id'], {"name": new_name, "status": new_status})
504
st.session_state.edit_item = None
505
st.success("Item updated!")
506
st.rerun()
507
508
with col2:
509
if st.button("Cancel"):
510
st.session_state.edit_item = None
511
st.rerun()
512
513
edit_item_dialog()
514
515
# Confirmation Dialog
516
if st.session_state.confirm_action:
517
@st.dialog("Confirm Action")
518
def confirmation_dialog():
519
action = st.session_state.confirm_action
520
521
if action.startswith("delete_"):
522
item_id = action.split("_")[1]
523
st.warning(f"Are you sure you want to delete item {item_id}?")
524
st.write("This action cannot be undone.")
525
526
col1, col2 = st.columns(2)
527
with col1:
528
if st.button("Confirm", type="primary"):
529
execute_action(action)
530
st.session_state.confirm_action = None
531
st.success("Action completed!")
532
st.rerun()
533
534
with col2:
535
if st.button("Cancel"):
536
st.session_state.confirm_action = None
537
st.rerun()
538
539
confirmation_dialog()
540
```