π¬Β Β Stateful Chat
Submitted by Lukas Masuch
Summary
A chat container that automatically keeps track of the chat history.
Functions
add_message
Adds a chat message to the chat container.
This command can only be used inside the chat
container. The message
will be displayed in the UI and added to the chat history so that the same
message will be automatically displayed on reruns.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
Literal['user', 'assistant'] | str
|
The name of the message author. Can be βuserβ or βassistantβ to enable preset styling and avatars. Currently, the name is not shown in the UI but is only set as an accessibility label. For accessibility reasons, you should not use an empty string. |
required |
avatar |
str | AtomicImage | None
|
The avatar shown next to the message. Can be anything that is supported by
the |
None
|
*args |
Any
|
The content of the message. This can be any number of elements that are supported by
|
()
|
Source code in src/streamlit_extras/stateful_chat/__init__.py
Import:
- You should add this to the top of your .py file
chat
Insert a stateful chat container into your app.
This chat container automatically keeps track of the chat history when you use
the add_message
command to add messages to the chat.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key |
str
|
The key that is used to keep track of the chat history in session state. Defaults to "chat_messages". |
'chat_messages'
|
Returns:
Name | Type | Description |
---|---|---|
DeltaGenerator |
'DeltaGenerator'
|
Chat Container
The chat container that can be used together with |
Source code in src/streamlit_extras/stateful_chat/__init__.py
Import:
- You should add this to the top of your .py file
Examples
example
def example():
with chat(key="my_chat"):
if prompt := st.chat_input():
add_message("user", prompt, avatar="π§βπ»")
def stream_echo():
for word in prompt.split():
yield word + " "
time.sleep(0.15)
add_message("assistant", "Echo: ", stream_echo, avatar="π¦")