0
# User Management
1
2
User authentication, session management, and persistent data storage across conversations. These components enable building personalized conversational applications with user state management and secure authentication.
3
4
## Capabilities
5
6
### User Objects and Authentication
7
8
Represent users with authentication details and persistent metadata for personalized experiences.
9
10
```python { .api }
11
import chainlit as cl
12
13
class User:
14
"""
15
User representation for authentication and session management.
16
17
Args:
18
identifier: str - Unique user identifier (email, username, etc.)
19
display_name: Optional[str] - Human-readable display name
20
metadata: Dict - Additional user data and custom properties
21
22
Returns:
23
User instance for authentication and session tracking
24
"""
25
def __init__(
26
self,
27
identifier: str,
28
display_name: Optional[str] = None,
29
metadata: Dict = {}
30
): ...
31
32
class PersistedUser:
33
"""
34
Extended User class with database persistence fields.
35
36
Args:
37
identifier: str - Unique user identifier
38
display_name: Optional[str] - Human-readable display name
39
metadata: Dict - Additional user data
40
id: str - Database record ID
41
createdAt: str - Creation timestamp
42
43
Returns:
44
PersistedUser instance with database tracking
45
"""
46
def __init__(
47
self,
48
identifier: str,
49
display_name: Optional[str] = None,
50
metadata: Dict = {},
51
id: str = "",
52
createdAt: str = ""
53
): ...
54
```
55
56
Usage examples for user objects:
57
58
```python
59
import chainlit as cl
60
61
# Create a basic user
62
user = cl.User(
63
identifier="alice@example.com",
64
display_name="Alice Smith",
65
metadata={
66
"role": "admin",
67
"preferences": {"theme": "dark"},
68
"last_login": "2024-01-15"
69
}
70
)
71
72
# Access user properties
73
print(f"User: {user.display_name} ({user.identifier})")
74
print(f"Role: {user.metadata.get('role')}")
75
76
# Persisted user with database fields
77
persisted_user = cl.PersistedUser(
78
identifier="bob@example.com",
79
display_name="Bob Johnson",
80
metadata={"department": "engineering"},
81
id="user_12345",
82
createdAt="2024-01-01T00:00:00Z"
83
)
84
```
85
86
### Session Management
87
88
Store and retrieve user-specific data across conversations with typed accessors and built-in session fields.
89
90
```python { .api }
91
class UserSession:
92
"""
93
Session storage for user-specific data between interactions.
94
Accessible via the global `user_session` object.
95
96
Built-in fields:
97
id: str - Session identifier
98
env: Dict - Environment variables
99
chat_settings: Dict - Current chat settings
100
user: Optional[User] - Authenticated user object
101
chat_profile: Optional[str] - Active chat profile
102
client_type: str - Client type (web, mobile, etc.)
103
"""
104
105
def get(self, key: str, default: Any = None) -> Any:
106
"""
107
Retrieve a value from the session.
108
109
Args:
110
key: str - Session key to retrieve
111
default: Any - Default value if key not found
112
113
Returns:
114
Stored value or default
115
"""
116
117
def set(self, key: str, value: Any) -> None:
118
"""
119
Store a value in the session.
120
121
Args:
122
key: str - Session key to store
123
value: Any - Value to store
124
"""
125
126
def create_accessor(
127
self,
128
key: str,
129
default: Any = None,
130
apply_fn: Optional[Callable] = None
131
) -> Callable:
132
"""
133
Create a typed accessor for a session key.
134
135
Args:
136
key: str - Session key
137
default: Any - Default value for the key
138
apply_fn: Optional[Callable] - Transform function for the value
139
140
Returns:
141
Callable accessor function
142
"""
143
144
# Global session object available in all callback contexts
145
user_session: UserSession
146
```
147
148
Usage examples for session management:
149
150
```python
151
import chainlit as cl
152
153
@cl.on_chat_start
154
async def start():
155
"""Initialize user session data"""
156
# Store user preferences
157
cl.user_session.set("user_preferences", {
158
"language": "en",
159
"notifications": True,
160
"theme": "light"
161
})
162
163
# Store conversation context
164
cl.user_session.set("conversation_history", [])
165
cl.user_session.set("current_topic", None)
166
167
# Access built-in session fields
168
user = cl.user_session.get("user")
169
if user:
170
await cl.Message(f"Welcome back, {user.display_name}!").send()
171
else:
172
await cl.Message("Welcome! Please sign in to continue.").send()
173
174
@cl.on_message
175
async def handle_message(message: cl.Message):
176
# Retrieve session data
177
preferences = cl.user_session.get("user_preferences", {})
178
history = cl.user_session.get("conversation_history", [])
179
180
# Update conversation history
181
history.append({
182
"timestamp": "2024-01-15T10:30:00Z",
183
"message": message.content,
184
"type": "user"
185
})
186
cl.user_session.set("conversation_history", history)
187
188
# Use preferences in response
189
language = preferences.get("language", "en")
190
response = f"[{language}] Processing your message..."
191
await cl.Message(response).send()
192
193
# Track conversation state
194
cl.user_session.set("last_interaction", "2024-01-15T10:30:00Z")
195
196
# Create typed accessors for common session data
197
@cl.on_chat_start
198
async def setup_accessors():
199
# Create accessor with default value
200
get_user_score = cl.user_session.create_accessor("user_score", default=0)
201
202
# Create accessor with transform function
203
get_user_level = cl.user_session.create_accessor(
204
"user_level",
205
default="beginner",
206
apply_fn=str.lower
207
)
208
209
# Use accessors
210
score = get_user_score() # Returns 0 if not set
211
level = get_user_level() # Returns "beginner" and lowercases value
212
213
await cl.Message(f"Your level: {level}, Score: {score}").send()
214
215
@cl.on_settings_update
216
async def handle_settings_update(settings: Dict[str, Any]):
217
"""Handle chat settings changes"""
218
# Store updated settings in session
219
cl.user_session.set("chat_settings", settings)
220
221
# Access via built-in field
222
current_settings = cl.user_session.chat_settings
223
224
await cl.Message("Settings updated successfully!").send()
225
226
# Access session data across different callbacks
227
@cl.on_chat_resume
228
async def resume_chat(thread_dict: Dict):
229
"""Restore session state when resuming a chat"""
230
# Restore conversation context
231
cl.user_session.set("thread_id", thread_dict.get("id"))
232
233
# Load user-specific data
234
user = cl.user_session.get("user")
235
if user:
236
# Restore user preferences from metadata
237
preferences = user.metadata.get("preferences", {})
238
cl.user_session.set("user_preferences", preferences)
239
240
await cl.Message(f"Resuming conversation, {user.display_name}").send()
241
242
@cl.on_chat_end
243
async def cleanup_session():
244
"""Clean up session data when chat ends"""
245
# Save important session data before cleanup
246
final_score = cl.user_session.get("user_score", 0)
247
conversation_summary = cl.user_session.get("conversation_summary", "")
248
249
# Store in user metadata for next session
250
user = cl.user_session.get("user")
251
if user:
252
user.metadata.update({
253
"last_score": final_score,
254
"last_summary": conversation_summary
255
})
256
```
257
258
### Chat Profiles and Context
259
260
Manage different chat modes and conversation contexts with profile-specific configurations.
261
262
```python { .api }
263
@dataclass
264
class ChatProfile:
265
"""
266
Chat profile configuration for different conversation modes.
267
268
Fields:
269
name: str - Profile identifier
270
markdown_description: str - Profile description in markdown
271
icon: Optional[str] - Icon name for the profile
272
default: bool - Whether this is the default profile
273
starters: Optional[List[Starter]] - Profile-specific conversation starters
274
"""
275
name: str
276
markdown_description: str
277
icon: Optional[str] = None
278
default: bool = False
279
starters: Optional[List[Starter]] = None
280
281
@dataclass
282
class Starter:
283
"""
284
Conversation starter configuration for chat profiles.
285
286
Fields:
287
label: str - Display text for the starter
288
message: str - Message content when starter is selected
289
command: Optional[str] - Optional command identifier
290
icon: Optional[str] - Icon name for the starter
291
"""
292
label: str
293
message: str
294
command: Optional[str] = None
295
icon: Optional[str] = None
296
```
297
298
Usage examples for chat profiles:
299
300
```python
301
import chainlit as cl
302
303
@cl.set_chat_profiles
304
async def chat_profiles(user: Optional[cl.User]) -> List[cl.ChatProfile]:
305
"""Define available chat profiles for users"""
306
profiles = [
307
cl.ChatProfile(
308
name="assistant",
309
markdown_description="General AI assistant for questions and tasks",
310
icon="message-circle",
311
default=True,
312
starters=[
313
cl.Starter(
314
label="Ask a question",
315
message="What would you like to know?",
316
icon="help-circle"
317
),
318
cl.Starter(
319
label="Get help with coding",
320
message="I need help with coding",
321
icon="code"
322
)
323
]
324
),
325
cl.ChatProfile(
326
name="analyst",
327
markdown_description="Data analysis and visualization expert",
328
icon="bar-chart-3",
329
starters=[
330
cl.Starter(
331
label="Analyze data",
332
message="Help me analyze my dataset",
333
icon="trending-up"
334
),
335
cl.Starter(
336
label="Create visualization",
337
message="Create a chart from my data",
338
icon="pie-chart"
339
)
340
]
341
)
342
]
343
344
# Filter profiles based on user permissions
345
if user and user.metadata.get("role") == "admin":
346
profiles.append(
347
cl.ChatProfile(
348
name="admin",
349
markdown_description="Administrative functions and system management",
350
icon="settings",
351
starters=[
352
cl.Starter(
353
label="System status",
354
message="Show system status",
355
icon="activity"
356
)
357
]
358
)
359
)
360
361
return profiles
362
363
@cl.on_chat_start
364
async def handle_profile_start():
365
"""Handle chat initialization based on selected profile"""
366
# Get current chat profile from session
367
profile = cl.user_session.get("chat_profile")
368
369
if profile == "assistant":
370
await cl.Message("Hi! I'm your AI assistant. How can I help you today?").send()
371
elif profile == "analyst":
372
await cl.Message("Hello! I'm here to help with data analysis. Upload your data or ask me about analytics.").send()
373
elif profile == "admin":
374
await cl.Message("Admin mode activated. What would you like to manage?").send()
375
else:
376
await cl.Message("Welcome! Please select a chat profile to get started.").send()
377
378
@cl.on_message
379
async def handle_profile_message(message: cl.Message):
380
"""Handle messages based on active chat profile"""
381
profile = cl.user_session.get("chat_profile", "assistant")
382
383
if profile == "analyst":
384
# Handle data analysis requests
385
if "upload" in message.content.lower() or "data" in message.content.lower():
386
files = await cl.AskFileMessage(
387
content="Please upload your data file:",
388
accept=["text/csv", "application/json", "text/plain"]
389
).send()
390
391
if files:
392
await cl.Message("Data received! Analyzing...").send()
393
# Process uploaded data
394
395
elif profile == "admin":
396
# Handle admin commands
397
if message.content.lower().startswith("/status"):
398
await cl.Message("System Status: All services running normally").send()
399
400
# Default assistant behavior for all profiles
401
await cl.Message(f"[{profile}] Processing: {message.content}").send()
402
```
403
404
## Core Types
405
406
```python { .api }
407
from typing import Optional, Dict, Any, List, Callable
408
from dataclasses import dataclass
409
410
# User and session types
411
class UserMetadata(Dict[str, Any]):
412
"""Type hint for user metadata dictionary"""
413
pass
414
415
# Session accessor function type
416
SessionAccessor = Callable[[], Any]
417
418
# Thread dictionary structure for chat resume
419
ThreadDict = Dict[str, Any] # Contains thread metadata and history
420
```