0
# Chat Interface
1
2
Complete chat interface system for building conversational applications with message feeds, input areas, and reaction components. The chat system provides a full-featured messaging interface with support for different message types, user avatars, reactions, and customizable styling.
3
4
## Capabilities
5
6
### Complete Chat Interface
7
8
Full-featured chat interface combining all chat components into a ready-to-use conversational UI.
9
10
```python { .api }
11
class ChatInterface:
12
"""
13
Complete chat interface component with message feed and input area.
14
15
Parameters:
16
- callback: Function to handle new messages
17
- callback_user: User identifier for callback function
18
- callback_exception: How to handle callback exceptions ('summary', 'verbose', 'ignore')
19
- show_rerun: Whether to show rerun button for messages
20
- show_undo: Whether to show undo button for messages
21
- show_clear: Whether to show clear button
22
- **params: Additional parameters
23
"""
24
```
25
26
### Message Feed
27
28
Scrollable container for displaying chat messages with support for different message types and styling.
29
30
```python { .api }
31
class ChatFeed:
32
"""
33
Message feed component for displaying chat messages.
34
35
Parameters:
36
- objects: List of message objects to display
37
- load_buffer: Number of messages to load ahead for performance
38
- scroll_button_threshold: Threshold for showing scroll-to-bottom button
39
- auto_scroll_limit: Message limit for automatic scrolling
40
- show_activity_dot: Whether to show activity indicator
41
- **params: Additional parameters
42
"""
43
```
44
45
### Individual Messages
46
47
Components for creating and displaying individual chat messages with various content types.
48
49
```python { .api }
50
class ChatMessage:
51
"""
52
Individual chat message component.
53
54
Parameters:
55
- object: Message content (text, HTML, or Panel object)
56
- user: User name or identifier
57
- avatar: User avatar image or initials
58
- timestamp: Message timestamp
59
- reactions: List of reaction emojis
60
- show_reaction_icons: Whether to show reaction buttons
61
- show_copy_icon: Whether to show copy button
62
- show_timestamp: Whether to show message timestamp
63
- **params: Additional parameters
64
"""
65
```
66
67
### Chat Steps
68
69
Components for representing multi-step conversations or workflows within chat.
70
71
```python { .api }
72
class ChatStep:
73
"""
74
Chat step component for multi-step conversations.
75
76
Parameters:
77
- object: Step content
78
- title: Step title
79
- status: Step status ('pending', 'running', 'complete', 'failed')
80
- **params: Additional parameters
81
"""
82
```
83
84
### Input Components
85
86
Specialized input components designed for chat interfaces.
87
88
```python { .api }
89
class ChatAreaInput:
90
"""
91
Chat input area with send button and formatting options.
92
93
Parameters:
94
- value: Current input text
95
- placeholder: Placeholder text for input
96
- max_rows: Maximum number of visible rows
97
- auto_grow: Whether input area grows with content
98
- disabled: Whether input is disabled
99
- **params: Additional parameters
100
"""
101
```
102
103
### Reaction Components
104
105
Components for displaying and managing message reactions.
106
107
```python { .api }
108
class ChatReactionIcons:
109
"""
110
Reaction icons component for message reactions.
111
112
Parameters:
113
- value: Currently selected reactions
114
- options: Available reaction options
115
- **params: Additional parameters
116
"""
117
```
118
119
## Usage Examples
120
121
### Basic Chat Interface
122
123
```python
124
import panel as pn
125
126
def respond_to_message(contents, user, instance):
127
"""Callback function to handle new messages"""
128
if "hello" in contents.lower():
129
return "Hello! How can I help you today?"
130
else:
131
return f"You said: {contents}"
132
133
# Create chat interface
134
chat = pn.chat.ChatInterface(
135
callback=respond_to_message,
136
callback_user="Assistant",
137
show_rerun=True,
138
show_undo=True
139
)
140
141
chat.servable()
142
```
143
144
### Custom Chat Feed
145
146
```python
147
# Create messages
148
messages = [
149
pn.chat.ChatMessage(
150
"Welcome to our support chat!",
151
user="Support Agent",
152
avatar="๐ง"
153
),
154
pn.chat.ChatMessage(
155
"Hi, I need help with my account.",
156
user="Customer",
157
avatar="๐ค"
158
),
159
pn.chat.ChatMessage(
160
"I'd be happy to help! What specific issue are you experiencing?",
161
user="Support Agent",
162
avatar="๐ง"
163
)
164
]
165
166
# Create chat feed
167
chat_feed = pn.chat.ChatFeed(
168
*messages,
169
load_buffer=50,
170
scroll_button_threshold=5,
171
show_activity_dot=True
172
)
173
174
# Add input area
175
input_area = pn.chat.ChatAreaInput(
176
placeholder="Type your message here...",
177
max_rows=5
178
)
179
180
# Combine into layout
181
chat_layout = pn.Column(
182
chat_feed,
183
input_area,
184
sizing_mode='stretch_both',
185
height=600
186
)
187
```
188
189
### Multi-Step Chat Workflow
190
191
```python
192
# Create step-based conversation
193
steps = [
194
pn.chat.ChatStep(
195
"Analyzing your request...",
196
title="Step 1: Analysis",
197
status="complete"
198
),
199
pn.chat.ChatStep(
200
"Fetching relevant data...",
201
title="Step 2: Data Retrieval",
202
status="running"
203
),
204
pn.chat.ChatStep(
205
"Generating response...",
206
title="Step 3: Response Generation",
207
status="pending"
208
)
209
]
210
211
workflow_chat = pn.chat.ChatFeed(*steps)
212
```
213
214
### Advanced Chat with Reactions
215
216
```python
217
# Create message with reactions
218
message_with_reactions = pn.chat.ChatMessage(
219
"This feature is really useful! ๐",
220
user="User",
221
avatar="https://example.com/avatar.jpg",
222
reactions=["๐", "โค๏ธ", "๐"],
223
show_reaction_icons=True,
224
show_copy_icon=True,
225
show_timestamp=True
226
)
227
228
# Create reaction icons component
229
reaction_icons = pn.chat.ChatReactionIcons(
230
options=["๐", "๐", "โค๏ธ", "๐", "๐ฎ", "๐ข", "๐"],
231
value=["๐", "โค๏ธ"]
232
)
233
```
234
235
### Custom Chat Styling
236
237
```python
238
# Create styled chat interface
239
styled_chat = pn.chat.ChatInterface(
240
callback=respond_to_message,
241
callback_user="AI Assistant",
242
width=800,
243
height=600,
244
margin=(10, 10),
245
styles={
246
'background': '#f8f9fa',
247
'border': '1px solid #dee2e6',
248
'border-radius': '8px'
249
}
250
)
251
252
# Customize message appearance
253
custom_message = pn.chat.ChatMessage(
254
"This is a custom styled message",
255
user="User",
256
avatar="๐ค",
257
styles={
258
'background': '#e3f2fd',
259
'border-left': '4px solid #2196f3',
260
'padding': '10px',
261
'margin': '5px 0'
262
}
263
)
264
```
265
266
### Persistent Chat History
267
268
```python
269
import param
270
271
class PersistentChat(param.Parameterized):
272
messages = param.List(default=[])
273
274
def __init__(self, **params):
275
super().__init__(**params)
276
self.chat_interface = pn.chat.ChatInterface(
277
callback=self.handle_message,
278
callback_user="Assistant"
279
)
280
self.load_history()
281
282
def handle_message(self, contents, user, instance):
283
# Process message and generate response
284
response = self.generate_response(contents)
285
286
# Save to history
287
self.messages.extend([
288
{'user': user, 'message': contents},
289
{'user': 'Assistant', 'message': response}
290
])
291
self.save_history()
292
293
return response
294
295
def load_history(self):
296
# Load previous messages from storage
297
for msg in self.messages:
298
self.chat_interface.send(
299
msg['message'],
300
user=msg['user'],
301
respond=False
302
)
303
304
def save_history(self):
305
# Save messages to persistent storage
306
pass
307
308
persistent_chat = PersistentChat()
309
```
310
311
## Integration with Other Systems
312
313
### Chat with Data Analysis
314
315
```python
316
import pandas as pd
317
318
def data_analysis_chat(contents, user, instance):
319
"""Chat interface for data analysis queries"""
320
query = contents.lower()
321
322
if "show data" in query:
323
return pn.pane.DataFrame(df.head())
324
elif "plot" in query:
325
import matplotlib.pyplot as plt
326
fig, ax = plt.subplots()
327
df.plot(ax=ax)
328
return pn.pane.Matplotlib(fig)
329
elif "summary" in query:
330
return pn.pane.Str(str(df.describe()))
331
else:
332
return "I can help you with data analysis. Try 'show data', 'plot', or 'summary'."
333
334
data_chat = pn.chat.ChatInterface(
335
callback=data_analysis_chat,
336
callback_user="Data Assistant"
337
)
338
```
339
340
### Chat with File Processing
341
342
```python
343
def file_processing_chat(contents, user, instance):
344
"""Chat interface with file processing capabilities"""
345
if contents.startswith("/upload"):
346
file_input = pn.widgets.FileInput(accept='.csv,.xlsx')
347
return pn.Column(
348
"Please select a file to upload:",
349
file_input
350
)
351
elif contents.startswith("/analyze"):
352
# Process uploaded file
353
return "File analysis complete! Here are the results..."
354
else:
355
return "Available commands: /upload, /analyze"
356
357
file_chat = pn.chat.ChatInterface(
358
callback=file_processing_chat,
359
callback_user="File Assistant"
360
)
361
```