Custom backgroung color using st.chat_message()

  import streamlit as st
  st.html(
  """
      <style>
      .clickable {
          color: rgb(46, 154, 255);
          text-decoration: underline;
      }
  
  div[data-testid="stChatMessageContent"] {
      background-color: #ffd9b3;
      color: black; # Expander content color
  } 
  
  div[data-testid="stChatMessage"] {
      background-color: #ffd9b3;
      color: black; # Adjust this for expander header color
  }
  </style>
  """)
  
  with st.chat_message(name='user'):
      st.write('Hello User')
  
  with st.chat_message(name='assistant'):
      st.write('Hello assistant')

Hi @blackary , I’m trying to customize my Streamlit chatbot by applying different background colors for the user and assistant messages to improve readability. However, I’m unable to get it working.

Could you suggest how I can apply different custom background colors for the user and assistant messages? Thanks! :blush:

Here’s one way to do it:

  1. Put each st.chat_message into a container with a key
  2. Make that key either user or assistant (plus a random string because you can’t have have two elements with the same key
  3. Find elements that contain the class st-key-user or st-key-assistant and use that to style them
import uuid

import streamlit as st

st.html(
    """
  <style>
    [class*="st-key-user"] {
        background-color: #a3a3a3;
    }

    [class*="st-key-assistant"] {
        background-color: #b3ffb3;
    }
  </style>
  """
)


def chat_message(name):
    return st.container(key=f"{name}-{uuid.uuid4()}").chat_message(name=name)


with chat_message(name="user"):
    st.write("Hello User")

with chat_message(name="assistant"):
    st.write("Hello assistant")

Playground link: Playground • Streamlit

2 Likes

thanks @blackary , its working :blush:

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.