Skip to main content

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

Project description

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 site.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

streamlit_rich_message_history-0.1.5.tar.gz (13.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

streamlit_rich_message_history-0.1.5-py3-none-any.whl (15.1 kB view details)

Uploaded Python 3

File details

Details for the file streamlit_rich_message_history-0.1.5.tar.gz.

File metadata

  • Download URL: streamlit_rich_message_history-0.1.5.tar.gz
  • Upload date:
  • Size: 13.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.1 CPython/3.11.11 Linux/6.8.0-1021-azure

File hashes

Hashes for streamlit_rich_message_history-0.1.5.tar.gz
Algorithm Hash digest
SHA256 79642c3e4542f82910ec9442c84dcb6dd99936cb486a58047109bae69d9c94ee
MD5 a8dc3e5e9254f2c3eeaf5a52d24ea2ab
BLAKE2b-256 8be0fe9e7a498d5f79e0909ebf13298e6314e7c4ad058a6c74da37c3edc3ba1f

See more details on using hashes here.

File details

Details for the file streamlit_rich_message_history-0.1.5-py3-none-any.whl.

File metadata

File hashes

Hashes for streamlit_rich_message_history-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 046589ecc72241c2b5ad23e0153ac3a4300c27db4c68a04fadd5674f03c1b0d0
MD5 67b14cba0815b5ce8567cb1a8abe5b14
BLAKE2b-256 49feb42323837bf23074c7ee0944bf0910d2ab05c67e005c8268727b3975987c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page