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:
- st.chat_input() → to capture user input
- st.session_state → to store conversation history
Basic Syntax
st.chat_message(name)
The function has the following parameters:
- name: Who sent the message ("user", "assistant", "ai")
- avatar: Optional emoji or image
- name: Custom label for the sender
Example:
Python
import streamlit as st
st.chat_message("user").write("Hello!")
st.chat_message("assistant").write("Hi, how can I help you?") ✔ Output
- User message bubble
- Assistant reply bubble
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:
- emojis
- image URLs
- local images