Skip to main content

Streamlit Rich Message History

A Python package for creating rich, multi-component chat messages in Streamlit.

Installation

pip

pip install streamlit-rich-message-history

poetry

poetry add streamlit-rich-message-history

Basic Usage

import streamlit as st
from streamlit_rich_message_history import MessageHistory, UserMessage, AssistantMessage

# Initialize message history
history = MessageHistory()

# Add a simple user message
history.add_user_message_create("👤", "Hello, I need data analysis help")

# Create a rich assistant response
assistant_msg = AssistantMessage("🤖")
assistant_msg.add_text("I'd be happy to help! Here's a sample dataframe:")

import pandas as pd
import numpy as np

# Create a sample dataframe
df = pd.DataFrame({
    'A': np.random.randn(5),
    'B': np.random.randn(5),
    'C': np.random.randn(5)
})

# Add components to the message
assistant_msg.add_dataframe(df, title="Sample Data")
assistant_msg.add_code("import pandas as pd\ndf = pd.read_csv('data.csv')", 
                      language="python", 
                      title="Loading Data Code")

# Add the message to history
history.add_assistant_message(assistant_msg)

# Render all messages
history.render_all()

Features

  • Multi-component chat messages
  • Automatic type detection
  • Support for various content types:
    • Text and Markdown
    • DataFrames and Series
    • Matplotlib and Plotly figures
    • Code blocks with syntax highlighting
    • Error messages
    • Metrics
    • And more!
  • Custom component types

Custom Component Types

One of the powerful features of this package is the ability to create your own custom component types. This allows you to extend the package to display any type of content in your Streamlit app.

Creating a Custom Video Component

Here's a complete example of creating a custom video component:

import streamlit as st
from streamlit_rich_message_history import MessageHistory

# Initialize the message history
history = MessageHistory()

# Step 1: Register the video component type
VIDEO_TYPE = history.register_component_type("video")

# Step 2: Register a renderer for videos
def video_renderer(content, kwargs):
    st.video(content, start_time=kwargs.get("start_time", 0))

history.register_component_renderer(VIDEO_TYPE, video_renderer)

# Step 3: Register the add_video() method
history.register_component_method("add_video", VIDEO_TYPE)

# Now you can use add_video() directly in your application:
assistant_msg = history.add_assistant_message_create("🤖")
assistant_msg.add_text("Here's a sample video:")

# Use the new add_video method directly
assistant_msg.add_video(
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ", 
    start_time=0
)

# Render all messages
history.render_all()

Custom Component with Type Detection

You can also register a detector function that will automatically detect your custom content type:

# Register a detector for video content
def video_detector(content, kwargs):
    return isinstance(content, str) and (
        content.endswith(".mp4") or 
        "youtube.com" in content or 
        "vimeo.com" in content or
        kwargs.get("is_video", False)
    )

history.register_component_detector(VIDEO_TYPE, video_detector)

# Now you can add videos without explicitly using add_video
assistant_msg = history.add_assistant_message_create("🤖")
assistant_msg.add("https://www.youtube.com/watch?v=dQw4w9WgXcQ")  # Will be detected as video

Custom Method Implementation

You can provide your own implementation for the custom component method:

# Create a custom implementation with validation and preprocessing
def custom_video_method(self, url, start_time=0, **kwargs):
    """Add a video to the message with custom validation."""
    if not isinstance(url, str):
        raise TypeError("URL must be a string")
    
    # Normalize YouTube URLs
    if "youtube.com/watch?v=" in url:
        # Extract video ID and format URL
        video_id = url.split("watch?v=")[1].split("&")[0]
        url = f"https://youtube.com/watch?v={video_id}"
    
    return self.add_custom(url, component_type="video", start_time=start_time, **kwargs)

# Register with custom implementation
history.register_component_method("add_video", VIDEO_TYPE, custom_video_method)

Documentation

For more examples and detailed documentation, visit our documentation.

License

MIT

Metadata

Release files for streamlit-rich-message-history 0.1.11

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for streamlit-rich-message-history 0.1.11
File Size Uploaded
streamlit_rich_message_history-0.1.11.tar.gz 13.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for streamlit-rich-message-history 0.1.11
File Interpreter ABI Platform
streamlit_rich_message_history-0.1.11-py3-none-any.whl Python 3 none any Details

Total release size: 29.6 kB

Release files / streamlit_rich_message_history-0.1.11.tar.gz

Download URL streamlit_rich_message_history-0.1.11.tar.gz
Size 13.3 kB
Tags Source
SHA-256 checksum
How to use checksums
fad4287f135cdfa7035f11f6903a9f6959eae544df91b38f0f2e1565db593a25
BLAKE2b-256 checksum
How to use checksums
2f79c95a0c25b90522e2d5cebb6d05958caa6b3934e04f2a7099453f20697e32
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.3.3 CPython/3.11.15 Linux/6.17.0-1008-azure

Release files / streamlit_rich_message_history-0.1.11-py3-none-any.whl

Download URL streamlit_rich_message_history-0.1.11-py3-none-any.whl
Size 16.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
22760473218aa919cf7f1edd5a416d1dc97b8d481b8f9830c0f382dc55db5df8
BLAKE2b-256 checksum
How to use checksums
fb96f2eb23ab9b7612fda93c4469a865aa92c5b3e3f9096edbac475eeb74ed1c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.3.3 CPython/3.11.15 Linux/6.17.0-1008-azure

Release history Release notifications | RSS feed

This release

0.1.11 This release

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page