St.feedback with thumbs is not giving results

Here’s a toy example that saves the last user + AI message with feedback to a file. If a user doesn’t give feedback on some response, it’s skipped.

If you want to save then entire conversation, you could write all messages to the file and just append the feedback when given. You could also add the feedback to the message dict in Session State then write the whole conversation to a file when done. If you need to persist the feedback widgets in the conversation throughout, you’ll need to introduce keys (such as the numerical position of the message in the history) and maybe add a third key to the AI messages (“role”,“content”,“feedback”).

import streamlit as st

def bot():
    yield "Hi"

if "messages" not in st.session_state:
    st.session_state.messages = []
if "get_feedback" not in st.session_state:
    st.session_state.get_feedback = False

def save_feedback():
    with  open("myfile.txt", "a") as f:
        f.write(str(st.session_state.messages[-2]["role"])+"\n")
        f.write(str(st.session_state.messages[-2]["content"])+"\n")
        f.write(str(st.session_state.messages[-1]["role"])+"\n")
        f.write(str(st.session_state.messages[-1]["content"])+"\n")
        f.write(str(st.session_state.feedback)+"\n")
    st.session_state.get_feedback = False

for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

if prompt := st.chat_input("Say something"):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)
    with st.chat_message("assistant"):
        stream = bot() # Shorthand for some AI streamed
        response = st.write_stream(stream)
    st.session_state.messages.append({"role": "assistant", "content": response})
    st.session_state.get_feedback = True

if st.session_state.get_feedback:
    st.feedback("thumbs", key="feedback", on_change=save_feedback)