Strange behavior of UI elements

Why does for the following app when I submit the first query in the UI query element, the second UI query element appears right under the first one, the next top UI query element disappears, and the chat UI element appears? It happens only when the system processes the first query. After the first query, the layout is correct.

    # Create UI containers
    chat_history_container = st.container()
    query_container = st.container()
    agent_thoughts_container = st.container()
    plot_container = st.container()
    current_dataframe_container = st.container()

    with query_container.form(key="query"):
        query = st.text_input("", value="", type="default", 
            placeholder="e-g : How many rows ? "
            )
        submitted_query = st.form_submit_button("Submit")
        reset_chat_button = st.form_submit_button("Reset Chat")
        if reset_chat_button:
            st.session_state["chat_history"] = []
    if submitted_query:
        result, captured_output = csv_agent.get_agent_response(df, query, plot_container)
        cleaned_thoughts = csv_agent.process_agent_thoughts(captured_output)
        with agent_thoughts_container:
            csv_agent.display_agent_thoughts(cleaned_thoughts)
        csv_agent.update_chat_history(query, result)
        with chat_history_container:
            csv_agent.display_chat_history()
    if st.session_state.df is not None:
        with current_dataframe_container:
            st.subheader("Current dataframe:")
            st.write(st.session_state.df)

here screenshots (note that after first query submitted there are two UI elements for query for some reason).

here it how it looks before query submitted:

query is put into field:

query submitted (>>> problem is only here <<<):

chat with answer appears:

let’s try to submit one more query:

chat updated:

You should try putting query_container = st.container() first and the chat history beneath it.

@Akshat_Punia thank you for response, but I want query_container bellow chat_history_container