st.chat_message() in Streamlit

The chat_message method is used to display messages in a chat-style conversation layout. It creates message bubbles similar to ChatGPT, WhatsApp, or Slack.

It is typically used together with:

Basic Syntax

st.chat_message(name)    

The function has the following parameters:

Example:

Python

import streamlit as st

st.chat_message("user").write("Hello!")
st.chat_message("assistant").write("Hi, how can I help you?")    

Output

Using Context Manager (Best Practice)

Using with allows us to add multiple elements such as text, charts, and tables inside a single message bubble.

Python

import streamlit as st

with st.chat_message("assistant"):
    st.write("Here is a chart:")
    st.bar_chart([3, 7, 2, 5])    

Custom Avatar Example

Python

import streamlit as st

with st.chat_message("assistant", avatar="🤖"):
    st.write("I am your AI assistant")    

You can use: