There are multiple identical st.streamlit_chat.streamlit_chat widgets with the same generated key

I am new to streamlit and trying to navigate this error. I have tried adding keys to the components that require them, but I suspect that the issue is a little deeper. I have created a simple chatbot that calls OpenAI. This is working fine - I can send multiple queries and get the responses with no problem.

This code works fine:

prompt = st.text_input("Prompt", placeholder="Enter prompt here..", key="user_input")

with st.sidebar:
    with st.spinner("Loading..."):
        time.sleep(1)
    st.success("Done!")
if "user_prompt_history" not in st.session_state:
    st.session_state["user_prompt_history"] = []

if "chat_answers_history" not in st.session_state:
    st.session_state["chat_answers_history"] = []

if "chat_history" not in st.session_state:
    st.session_state["chat_history"] = []


def create_sources_string(source_urls: Set[str]) -> str:
    if not source_urls:
        return ""
    sources_list = list(source_urls)
    sources_list.sort()
    sources_string = "sources:\n"
    for i, source in enumerate(sources_list):
        sources_string += f"{i+1}. {source}\n"
    return sources_string


if prompt:
    with st.spinner("Generating response.."):
        generated_response = run_llm(
            query=prompt, chat_history=st.session_state["chat_history"]
        )
        sources = set(
            [doc.metadata["source"] for doc in generated_response["source_documents"]]
        )

        formatted_response = (
            f"{generated_response['answer']} \n\n {create_sources_string(sources)}"
        )

        st.session_state["user_prompt_history"].append(prompt)
        st.session_state["chat_answers_history"].append(formatted_response)
        st.session_state["chat_history"].append((prompt, generated_response["answer"]))

if st.session_state["chat_answers_history"]:
    for generated_response, user_query in zip(
        st.session_state["chat_answers_history"],
        st.session_state["user_prompt_history"],
    ):
        message(user_query, is_user=True)
        message(generated_response)

the problems start when I add in the button to clear the chat. Again, I can correspond with OpenAI just fine. When I click the button, I get the error. One thing to note: I see the chat box area attempt to refresh - could that be part of the issue? The last line in the error seems to indicate that.

The updated code (I added st.sidebar button and corresponding function)):

prompt = st.text_input("Prompt", placeholder="Enter prompt here..", key="user_input")

**def reset_conversation():**
**    st.session_state.conversation = [] # original value: None**
**    st.session_state.chat_history = [] # original value: None**
**    st.session_state.messages = []**

with st.sidebar:
    with st.spinner("Loading..."):
        time.sleep(1)
    st.success("Done!")
    st.sidebar.button('New Chat', on_click=reset_conversation, key="button1")

if "user_prompt_history" not in st.session_state:
    st.session_state["user_prompt_history"] = []

if "chat_answers_history" not in st.session_state:
    st.session_state["chat_answers_history"] = []

if "chat_history" not in st.session_state:
    st.session_state["chat_history"] = []


def create_sources_string(source_urls: Set[str]) -> str:
    if not source_urls:
        return ""
    sources_list = list(source_urls)
    sources_list.sort()
    sources_string = "sources:\n"
    for i, source in enumerate(sources_list):
        sources_string += f"{i+1}. {source}\n"
    return sources_string


if prompt:
    with st.spinner("Generating response.."):
        generated_response = run_llm(
            query=prompt, chat_history=st.session_state["chat_history"]
        )
        sources = set(
            [doc.metadata["source"] for doc in generated_response["source_documents"]]
        )

        formatted_response = (
            f"{generated_response['answer']} \n\n {create_sources_string(sources)}"
        )

        st.session_state["user_prompt_history"].append(prompt)
        st.session_state["chat_answers_history"].append(formatted_response)
        st.session_state["chat_history"].append((prompt, generated_response["answer"]))

if st.session_state["chat_answers_history"]:
    for generated_response, user_query in zip(
        st.session_state["chat_answers_history"],
        st.session_state["user_prompt_history"],
    ):
        message(user_query, is_user=True)
        message(generated_response)

The last part of the error references the last couple of lines in the code. Is that a clue?

hi,
st.session_state["chat_history"] , so it should be:

def reset_conversation():
    st.session_state["user_prompt_history"] = []
    st.session_state["chat_answers_history"] = []
    st.session_state["chat_history"] = []

Ah, thank you so much! I completely missed that! I really appreciate your help.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.