How to create a chat history on the side bar just like chatGPT?

A simple example is to save user/ai chat say in a csv. Add an id column to be used in building a button in the sidebar.

CSV

CSV_FILE = "chat_history.csv"
try:
    chat_history_df = pd.read_csv(CSV_FILE)
except FileNotFoundError:
    chat_history_df = pd.DataFrame(columns=["ChatID", "Role", "Content"])
                                  ChatID  Role                                            Content
0   982b1003-6e03-4f55-93a0-c2a29cabf6b8  User                                  what is streamlit
1   982b1003-6e03-4f55-93a0-c2a29cabf6b8    AI  Streamlit is an open-source Python library pri...
2   7807ab5f-0576-4022-9eab-3724c0c0590d  User                                     what is django
3   7807ab5f-0576-4022-9eab-3724c0c0590d    AI  Django is a high-level Python web framework th...
4   a063fe54-8274-4d5a-92a6-9ed3cc5b45ce  User                        what is flutter in 20 words
5   a063fe54-8274-4d5a-92a6-9ed3cc5b45ce    AI  Flutter is an open-source UI software developm...
6   72543195-39a2-46d2-ab6a-c412d2580028  User                         what is openai in 30 words
7   72543195-39a2-46d2-ab6a-c412d2580028    AI  OpenAI is an artificial intelligence research ...

Build buttons

def get_button_label(chat_df, chat_id):
    first_message = chat_df[(chat_df["ChatID"] == chat_id) & (chat_df["Role"] == "User")].iloc[0]["Content"]
    return f"Chat {chat_id[0:7]}: {' '.join(first_message.split()[:5])}..."


for chat_id in chat_history_df["ChatID"].unique():
    button_label = get_button_label(chat_history_df, chat_id)
    if st.sidebar.button(button_label):
        current_chat_id = chat_id
        loaded_chat = chat_history_df[chat_history_df["ChatID"] == chat_id]
        loaded_chat_string = "\n".join(f"{row['Role']}: {row['Content']}" for _, row in loaded_chat.iterrows())
        st.text_area("Chat History", value=loaded_chat_string, height=300)

Output

3 Likes