Copy to clipboard, copying the prompt & response prints it twice and feedback also dissappears

I am running app locally, trying to add copy to clipboard feature to a chatbot’s response , I tried using clipboard.

def on_copy_click(text):
# st.session_state.copied.append(text)
clipboard.copy(text)

Initialize chat history

if “messages” not in st.session_state:
st.session_state.messages =
count = 0

Display chat messages from history on app rerun

for message in st.session_state.messages:
with st.chat_message(message[“role”]):
st.markdown(message[“content”])
if message[“role”] == “assistant”:
st.button(“:clipboard:”, on_click=on_copy_click, args=(message[“content”],), key=count)
count += 1

React to user input

if prompt := st.chat_input(‘Your message here…’):
# Save this as a chat for later

if st.session_state.chat_id not in past_chats.keys():
    past_chats[st.session_state.chat_id] = st.session_state.chat_title
    joblib.dump(past_chats, 'data/past_chats_list')
# Display user message in chat message container
with st.chat_message('user'):
    st.markdown(prompt)
# Add user message to chat history
st.session_state.messages.append(
    dict(
        role='user',
        content=prompt,
    )
)  
## Send message to AI
response = st.session_state.chat.send_message(
    prompt,
    stream=True,
)
# Display assistant response in chat message container
with st.chat_message(
    name=MODEL_ROLE,
    avatar=AI_AVATAR_ICON,
):
    message_placeholder = st.empty()
    full_response = ''
    assistant_response = response
    # Streams in a chunk at a time
    for chunk in response:
        for ch in chunk.text.split(' '):
            full_response += ch + ' '
            time.sleep(0.05)
            # Rewrites with a cursor at end
            message_placeholder.write(full_response + '▌')
    # Write full message with placeholder
    message_placeholder.write(full_response)

# Add assistant response to chat history
st.session_state.messages.append(
    dict(
        role=MODEL_ROLE,
        content=st.session_state.chat.history[-1].parts[0].text,
        avatar=AI_AVATAR_ICON,
    )
)
st.button("📋", on_click=on_copy_click, args=(full_response,))

Its copying the prompt and response again and showing on the main screen
Before clicking on copy to clipboard-

After -

It look like the on_click causing to run the code again

You should try this first :

if st.button("📋"):
       on_copy_click(full_response)