Create a function which preserves session_state and ability to control the usage based on the engagement of user with app

I am trying to use counter variable that gives the user a message after reaching a certain threshold, lets say 3.
Please help me edit the code

if prompt := st.chat_input("What is up?"):
    
    counter=0
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        full_response = ""
        response_openai=openai.ChatCompletion.create(
            model=st.session_state["openai_model"],
            messages=[
                {"role": m["role"], "content": m["content"]}
                for m in st.session_state.messages
            ],
            temperature=0,
            stream=True,
        )

        for response in response_openai:
            full_response += response.choices[0].delta.get("content", "")
            message_placeholder.markdown(full_response + "▌")

            if counter>=2:
                st.warning("completed 3 respones")
                st.stop()

        message_placeholder.markdown(full_response)

    st.session_state.messages.append({"role": "assistant", "content": full_response})

What is the counter supposed to count?

number of responses by AI

Then I guess you should be increasing it by one as you iterate over the responses? I mean, actually counting them.

If you set counter=0 and never change it, it will never be the case that counter>=2.

Hey I think you forgot to increase the counter with each iteration :smile:, so your code will look something like

if prompt := st.chat_input("What is up?"):
    
    counter=0
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        full_response = ""
        response_openai=openai.ChatCompletion.create(
            model=st.session_state["openai_model"],
            messages=[
                {"role": m["role"], "content": m["content"]}
                for m in st.session_state.messages
            ],
            temperature=0,
            stream=True,
        )

        for response in response_openai:
            counter += 1 # this line you forgot
            full_response += response.choices[0].delta.get("content", "")
            message_placeholder.markdown(full_response + "▌")

            if counter>=2:
                st.warning("completed 3 respones")
                st.stop()

        message_placeholder.markdown(full_response)

    st.session_state.messages.append({"role": "assistant", "content": full_response})