😃Solved-St.chat_message,how to make google gemini chat.send_message() keep memory during multiple queries

I am working on a gemini-based chatbot . On the second query, the chat.send_message() can’t remember the context in the last query, gives totally new answer,can anybody tell me how to fix the problem?The code is following.

        # Display chat messages and bot response
    if st.session_state.messages[-1]["role"] != "assistant":
        with st.chat_message("assistant"):
            with st.spinner("Thinking..."):
                context = ""
                with open("context.txt", 'r', encoding='utf-8') as f:
                    text_docs = f.read()
                if len(text_docs) != 0:
                    context = text_docs
                    with open("context.txt", 'w', encoding='utf-8') as f:
                        f.truncate(0)
                response = chat.send_message(context + prompt)
                st.markdown(response.text)
                if response is not None:
                    message = {"role": "assistant", "content": response.text}
                    st.session_state.messages.append(message)


The context seems to be always the empty string, so there is nothing to remember.

The context get string from context.txt for the first time, then it is cleared by f.truncate(0).

So next time you read from context.txt you get the empty string.

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