The powerful data exploration & web app framework for Python.
—
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.
Full-featured chat interface combining all chat components into a ready-to-use conversational UI.
class ChatInterface:
"""
Complete chat interface component with message feed and input area.
Parameters:
- callback: Function to handle new messages
- callback_user: User identifier for callback function
- callback_exception: How to handle callback exceptions ('summary', 'verbose', 'ignore')
- show_rerun: Whether to show rerun button for messages
- show_undo: Whether to show undo button for messages
- show_clear: Whether to show clear button
- **params: Additional parameters
"""Scrollable container for displaying chat messages with support for different message types and styling.
class ChatFeed:
"""
Message feed component for displaying chat messages.
Parameters:
- objects: List of message objects to display
- load_buffer: Number of messages to load ahead for performance
- scroll_button_threshold: Threshold for showing scroll-to-bottom button
- auto_scroll_limit: Message limit for automatic scrolling
- show_activity_dot: Whether to show activity indicator
- **params: Additional parameters
"""Components for creating and displaying individual chat messages with various content types.
class ChatMessage:
"""
Individual chat message component.
Parameters:
- object: Message content (text, HTML, or Panel object)
- user: User name or identifier
- avatar: User avatar image or initials
- timestamp: Message timestamp
- reactions: List of reaction emojis
- show_reaction_icons: Whether to show reaction buttons
- show_copy_icon: Whether to show copy button
- show_timestamp: Whether to show message timestamp
- **params: Additional parameters
"""Components for representing multi-step conversations or workflows within chat.
class ChatStep:
"""
Chat step component for multi-step conversations.
Parameters:
- object: Step content
- title: Step title
- status: Step status ('pending', 'running', 'complete', 'failed')
- **params: Additional parameters
"""Specialized input components designed for chat interfaces.
class ChatAreaInput:
"""
Chat input area with send button and formatting options.
Parameters:
- value: Current input text
- placeholder: Placeholder text for input
- max_rows: Maximum number of visible rows
- auto_grow: Whether input area grows with content
- disabled: Whether input is disabled
- **params: Additional parameters
"""Components for displaying and managing message reactions.
class ChatReactionIcons:
"""
Reaction icons component for message reactions.
Parameters:
- value: Currently selected reactions
- options: Available reaction options
- **params: Additional parameters
"""import panel as pn
def respond_to_message(contents, user, instance):
"""Callback function to handle new messages"""
if "hello" in contents.lower():
return "Hello! How can I help you today?"
else:
return f"You said: {contents}"
# Create chat interface
chat = pn.chat.ChatInterface(
callback=respond_to_message,
callback_user="Assistant",
show_rerun=True,
show_undo=True
)
chat.servable()# Create messages
messages = [
pn.chat.ChatMessage(
"Welcome to our support chat!",
user="Support Agent",
avatar="🎧"
),
pn.chat.ChatMessage(
"Hi, I need help with my account.",
user="Customer",
avatar="👤"
),
pn.chat.ChatMessage(
"I'd be happy to help! What specific issue are you experiencing?",
user="Support Agent",
avatar="🎧"
)
]
# Create chat feed
chat_feed = pn.chat.ChatFeed(
*messages,
load_buffer=50,
scroll_button_threshold=5,
show_activity_dot=True
)
# Add input area
input_area = pn.chat.ChatAreaInput(
placeholder="Type your message here...",
max_rows=5
)
# Combine into layout
chat_layout = pn.Column(
chat_feed,
input_area,
sizing_mode='stretch_both',
height=600
)# Create step-based conversation
steps = [
pn.chat.ChatStep(
"Analyzing your request...",
title="Step 1: Analysis",
status="complete"
),
pn.chat.ChatStep(
"Fetching relevant data...",
title="Step 2: Data Retrieval",
status="running"
),
pn.chat.ChatStep(
"Generating response...",
title="Step 3: Response Generation",
status="pending"
)
]
workflow_chat = pn.chat.ChatFeed(*steps)# Create message with reactions
message_with_reactions = pn.chat.ChatMessage(
"This feature is really useful! 🎉",
user="User",
avatar="https://example.com/avatar.jpg",
reactions=["👍", "❤️", "🎉"],
show_reaction_icons=True,
show_copy_icon=True,
show_timestamp=True
)
# Create reaction icons component
reaction_icons = pn.chat.ChatReactionIcons(
options=["👍", "👎", "❤️", "😂", "😮", "😢", "🎉"],
value=["👍", "❤️"]
)# Create styled chat interface
styled_chat = pn.chat.ChatInterface(
callback=respond_to_message,
callback_user="AI Assistant",
width=800,
height=600,
margin=(10, 10),
styles={
'background': '#f8f9fa',
'border': '1px solid #dee2e6',
'border-radius': '8px'
}
)
# Customize message appearance
custom_message = pn.chat.ChatMessage(
"This is a custom styled message",
user="User",
avatar="👤",
styles={
'background': '#e3f2fd',
'border-left': '4px solid #2196f3',
'padding': '10px',
'margin': '5px 0'
}
)import param
class PersistentChat(param.Parameterized):
messages = param.List(default=[])
def __init__(self, **params):
super().__init__(**params)
self.chat_interface = pn.chat.ChatInterface(
callback=self.handle_message,
callback_user="Assistant"
)
self.load_history()
def handle_message(self, contents, user, instance):
# Process message and generate response
response = self.generate_response(contents)
# Save to history
self.messages.extend([
{'user': user, 'message': contents},
{'user': 'Assistant', 'message': response}
])
self.save_history()
return response
def load_history(self):
# Load previous messages from storage
for msg in self.messages:
self.chat_interface.send(
msg['message'],
user=msg['user'],
respond=False
)
def save_history(self):
# Save messages to persistent storage
pass
persistent_chat = PersistentChat()import pandas as pd
def data_analysis_chat(contents, user, instance):
"""Chat interface for data analysis queries"""
query = contents.lower()
if "show data" in query:
return pn.pane.DataFrame(df.head())
elif "plot" in query:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
df.plot(ax=ax)
return pn.pane.Matplotlib(fig)
elif "summary" in query:
return pn.pane.Str(str(df.describe()))
else:
return "I can help you with data analysis. Try 'show data', 'plot', or 'summary'."
data_chat = pn.chat.ChatInterface(
callback=data_analysis_chat,
callback_user="Data Assistant"
)def file_processing_chat(contents, user, instance):
"""Chat interface with file processing capabilities"""
if contents.startswith("/upload"):
file_input = pn.widgets.FileInput(accept='.csv,.xlsx')
return pn.Column(
"Please select a file to upload:",
file_input
)
elif contents.startswith("/analyze"):
# Process uploaded file
return "File analysis complete! Here are the results..."
else:
return "Available commands: /upload, /analyze"
file_chat = pn.chat.ChatInterface(
callback=file_processing_chat,
callback_user="File Assistant"
)