I got the solution now.
A key can be supplied to the streamlit_feedback() and this key can access the feedback value.
streamlit_feedback(feedback_type="thumbs", align="flex-start", key='fb_k')
The feedback can be completed in two ways. One, the user has to press the button represented by a thumb. Second if optional text is added, the feedback can be completed by 2 button clicks selecting the thumb and adding text.
This situation makes the chat app a little bit complicated because when the feedback button is clicked, streamlit will rerun the code from top to bottom. Now if there is a text option, it will rerun twice. To minimize this complication, we will use the form, so that there is only 1 exit to capture the feedback.
if question := st.chat_input(placeholder="Ask your question here .... !!!!"):
create_answer(question)
display_answer()
# This one.
with st.form('form'):
streamlit_feedback(feedback_type="thumbs", align="flex-start", key='fb_k')
st.form_submit_button('Save feedback', on_click=fbcb)
We can do anything of what the feedback is asking, once done, press the form button.
We also use the callback function fbcb
from click=fbcb
in the form button and this is where we update the history of the feedback.
def fbcb():
message_id = len(st.session_state.chat_history) - 1
if message_id >= 0:
st.session_state.chat_history[message_id]["feedback"] = st.session_state.fb_k
display_answer()
The value of the feedback can be accessed thru the key from the session_state.
st.session_state.fb_k
Sample output
Full code
import streamlit as st
from streamlit_feedback import streamlit_feedback
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
def display_answer():
for i in st.session_state.chat_history:
with st.chat_message("human"):
st.write(i["question"])
with st.chat_message("ai"):
st.write(i["answer"])
# If there is no feedback show N/A
if "feedback" in i:
st.write(f"Feedback: {i['feedback']}")
else:
st.write("Feedback: N/A")
def create_answer(question):
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
message_id = len(st.session_state.chat_history)
st.session_state.chat_history.append({
"question": question,
"answer": f"{question}_Answer",
"message_id": message_id,
})
def fbcb():
message_id = len(st.session_state.chat_history) - 1
if message_id >= 0:
st.session_state.chat_history[message_id]["feedback"] = st.session_state.fb_k
display_answer()
if question := st.chat_input(placeholder="Ask your question here .... !!!!"):
create_answer(question)
display_answer()
with st.form('form'):
streamlit_feedback(feedback_type="thumbs", align="flex-start", key='fb_k')
st.form_submit_button('Save feedback', on_click=fbcb)
Others
The streamlit_feedback
function has a parameter called on_submit
. This can also be used to get the feedback. I tried to apply that but did not work. But it will work in other situation.