Messages

Message classes for the streamlit_rich_message_history package.

This module defines the Message class and its derivatives (UserMessage, AssistantMessage, ErrorMessage) which represent chat messages with rich content components.

class streamlit_rich_message_history.messages.AssistantMessage(avatar)[source]

Bases: Message

Convenience class for assistant messages.

This class creates a Message with the ‘assistant’ role pre-configured, making it easier to create assistant/AI responses in a chat interface.

user

Always set to ‘assistant’

avatar

Avatar image for the assistant

components

List of MessageComponent objects in this message

__init__(avatar)[source]

Initialize a new assistant message.

Parameters:

avatar (str) – Avatar image for the assistant (URL or emoji)

class streamlit_rich_message_history.messages.ErrorMessage(avatar, error_text)[source]

Bases: Message

Convenience class for error messages.

This class creates a Message with the ‘error’ role pre-configured and automatically adds an error component, making it easier to display errors in a chat interface.

user

Always set to ‘error’

avatar

Avatar image for error messages

components

List of MessageComponent objects in this message

__init__(avatar, error_text)[source]

Initialize a new error message.

Parameters:
  • avatar (str) – Avatar image for the error message (URL or emoji)

  • error_text (str) – The error message to display

class streamlit_rich_message_history.messages.Message(user, avatar)[source]

Bases: object

Class representing a message with multiple components.

This is the core class for creating rich messages with various content types. A message represents a single chat bubble/entry that can contain multiple components (text, code, charts, tables, etc.).

user

The sender of the message (‘user’, ‘assistant’, etc.)

avatar

Avatar image for the message sender

components

List of MessageComponent objects in this message

__init__(user, avatar)[source]

Initialize a new message.

Parameters:
  • user (str) – The sender of the message (‘user’, ‘assistant’, etc.)

  • avatar (str) – Avatar image for the message sender (URL or emoji)

add(content, **kwargs)[source]

Add a component to the message with automatic type detection.

This is the core method for adding content. All specific add_* methods ultimately call this method with appropriate flags.

Parameters:
  • content (Any) – The content to add to the message

  • **kwargs – Additional keyword arguments that control rendering behavior Special flags include: - is_error: Treat string content as an error message - is_code: Treat string content as code with syntax highlighting - language: The programming language for code highlighting - is_metric: Treat numeric content as a metric - is_table: Treat content as a static table - is_json: Treat dictionaries or lists as JSON data - is_html: Treat string content as HTML

Returns:

Self, for method chaining

Return type:

Message

add_code(code, language='python', **kwargs)[source]

Add a code component to the message.

Parameters:
  • code (str) – The code snippet to display

  • language (str) – Programming language for syntax highlighting (default: ‘python’)

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_code("def hello(): print('Hello world')")
>>> message.add_code("<div>Hello</div>", language="html")
add_custom(content, component_type, **kwargs)[source]

Add a custom component type.

This method is used for components registered through the ComponentRegistry.

Parameters:
  • content (Any) – The content to display

  • component_type (str) – The registered component type name

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Raises:

ValueError – If the component type is not registered

Examples

>>> # After registering an 'image' component type:
>>> message.add_custom(my_pil_image, "image", width=300)
add_dataframe(df, **kwargs)[source]

Add a dataframe component to the message.

Parameters:
  • df (DataFrame) – The pandas DataFrame to display

  • **kwargs – Additional keyword arguments for the component Common ones include: - use_container_width: Whether to use the full container width - height: Height of the dataframe in pixels

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_dataframe(pd.DataFrame({'A': [1, 2], 'B': [3, 4]}))
>>> message.add_dataframe(df, height=300)
add_dict(items, **kwargs)[source]

Add a dictionary of items to the message.

Each value in the dictionary will be rendered as its own component.

Parameters:
  • items (Dict[str, Any]) – The dictionary of items to display

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_dict({"text": "Hello", "number": 42})
add_error(error_text, **kwargs)[source]

Add an error component to the message.

Parameters:
  • error_text (str) – The error message to display

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_error("File not found: example.txt")
add_html(html_content, **kwargs)[source]

Add an HTML component to the message.

Parameters:
  • html_content (str) – The HTML content to display

  • **kwargs – Additional keyword arguments for the component Common ones include: - height: Height of the HTML content in pixels - scrolling: Whether to enable scrolling

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_html("<h1>Hello World</h1>")
>>> message.add_html("<div>Content</div>", height=300, scrolling=True)
add_json(data, **kwargs)[source]

Add a JSON component to the message.

Parameters:
  • data (Union[Dict, List]) – The data to display as JSON

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_json({"name": "John", "age": 30})
>>> message.add_json([1, 2, 3, {"nested": True}])
add_list(items, **kwargs)[source]

Add a list of items to the message.

Each item in the list will be rendered as its own component.

Parameters:
  • items (List[Any]) – The list of items to display

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_list(["Text", 42, pd.DataFrame({'A': [1]})])
add_matplotlib_figure(fig, **kwargs)[source]

Add a matplotlib figure component to the message.

Parameters:
  • fig (Figure) – The matplotlib Figure to display

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3, 4])
>>> message.add_matplotlib_figure(fig)
add_metric(value, label=None, **kwargs)[source]

Add a metric component to the message.

Parameters:
  • value (Any) – The value of the metric

  • label (Optional[str]) – Label for the metric

  • **kwargs – Additional keyword arguments for the component Common ones include: - delta: Delta value to show - delta_color: Color for delta (‘normal’, ‘inverse’, ‘off’)

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_metric(42, "Answer")
>>> message.add_metric(103.5, "Temperature", delta=2.5)
add_number(number, **kwargs)[source]

Add a number component to the message.

Parameters:
  • number (Union[int, float]) – The number to display

  • **kwargs – Additional keyword arguments for the component Common ones include: - format: Format string (e.g., “{:.2f}%” for percentage) - title: Label for the number

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_number(42)
>>> message.add_number(3.14159, format="{:.2f}", title="Pi")
add_plotly_figure(fig, **kwargs)[source]

Add a plotly figure component to the message.

Parameters:
  • fig (Union[Figure, dict]) – The plotly Figure to display

  • **kwargs – Additional keyword arguments for the component Common ones include: - use_container_width: Whether to use the full container width - height: Height of the chart in pixels

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
>>> message.add_plotly_figure(fig)
add_series(series, **kwargs)[source]

Add a series component to the message.

Parameters:
  • series (Series) – The pandas Series to display

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_series(pd.Series([1, 2, 3, 4]))
add_table(data, **kwargs)[source]

Add a static table component to the message.

Parameters:
  • data (Any) – The data to display as a table

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_table(pd.DataFrame({'A': [1, 2], 'B': [3, 4]}))
>>> message.add_table([[1, 2], [3, 4]])
add_text(text, **kwargs)[source]

Add a text component to the message.

Parameters:
  • text (str) – The text content (supports markdown)

  • **kwargs – Additional keyword arguments for the component Common ones include: - title: A title for the text - description: A description

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_text("Hello, **world**!")
>>> message.add_text("Expandable content", title="Section Title")
add_tuple(items, **kwargs)[source]

Add a tuple of items to the message.

Each item in the tuple will be rendered as its own component.

Parameters:
  • items (Tuple[Any, ...]) – The tuple of items to display

  • **kwargs – Additional keyword arguments for the component

Returns:

Self, for method chaining

Return type:

Message

Examples

>>> message.add_tuple(("Text", 42, pd.DataFrame({'A': [1]})))
classmethod register_component_method(method_name, component_type, method_func=None)[source]

Register a new component method for the Message class. This method dynamically adds a new add_* method to the Message class for a custom component type. If a method with this name already exists, returns the existing method with a warning instead of raising an exception.

Parameters:
  • method_name (str) – Name of the method to add (typically ‘add_xyz’)

  • component_type (ComponentType) – The component type to associate with this method

  • method_func (Optional[Callable]) – Optional custom function for the method If None, a default implementation is created

Returns:

The created or existing method function

Return type:

Callable

Examples

>>> IMAGE_TYPE = ComponentRegistry.register_component_type("image")
>>> Message.register_component_method("add_image", IMAGE_TYPE)
>>> # Now message.add_image() is available
>>> # Registering the same method again will return the existing method
>>> Message.register_component_method("add_image", IMAGE_TYPE)
>>> # A warning will be printed and the existing method will be returned
render()[source]

Render the message with all its components.

This method displays the message in a Streamlit app using st.chat_message and renders all components within it.

Raises:

Displays an error message in the UI if rendering fails

class streamlit_rich_message_history.messages.UserMessage(avatar, text=None)[source]

Bases: Message

Convenience class for user messages.

This class creates a Message with the ‘user’ role pre-configured, making it easier to create user messages in a chat interface.

user

Always set to ‘user’

avatar

Avatar image for the user

components

List of MessageComponent objects in this message

__init__(avatar, text=None)[source]

Initialize a new user message.

Parameters:
  • avatar (str) – Avatar image for the user (URL or emoji)

  • text (Optional[str]) – Optional initial text for the message. If provided, adds a text component automatically.