Problem with editing and updating text_area() in a chatbot

Hi Everyone,

I’m trying to build a chatbot that takes user input, generate a query, display that query in a text_area (editable) and then have a button to run that query and display the resulting data as table.

Now, when the query is displayed, and I’m editing it, then I’m getting an error:

The handle_query_change() function is :

def handle_query_change(new_query):
    st.session_state.query_editable = new_query

and below is my code:

# Accept user input
if prompt := st.chat_input("Please ask your question"):
    # Display user message in chat message container
    with st.chat_message("user"):
    # Add user message to chat history
    st.session_state.messages.append({"role": "user", "content": prompt})

    query = generate_query(prompt)
    print('Original Query ---- ', query)
    # Display the generated SQL query
    st.subheader("Generated SQL Query:")
    query_editable = st.text_area("Generated SQL Query:", value=query, height=200, max_chars=None, on_change=handle_query_change)
    st.session_state["query_editable"] = query_editable
    print('After Edit Query ---- ', st.session_state.query_editable)

# Execute the SQL query when the "Run Query" button is clicked
if st.button("Run Query"):
    # Retrieve the edited query from session state
    query_editable = st.session_state.query_editable
    # Define query_editable here
    if query_editable.strip():  # Check if query_editable is not empty
        with st.spinner("Running query..."):
                result_data = raw_query(query_editable, as_df=True)  # Execute the query and return as DataFrame
                with st.chat_message("assistant"):
                    if isinstance(result_data, pd.DataFrame):
                        st.table(result_data)  # Display the result as a table
                        st.markdown(result_data)  # Display the result as markdown
                    st.session_state.messages.append({"role": "assistant", "content": result_data})  # Add assistant response to chat history
            except Exception as e:
                st.error(f"Error executing the query: {e}")
        st.error("Please enter a valid SQL query before running.")

After editing, its not getting updated, I’m getting the same query as the original query.

Attaching the link of the video for the same:

It’d be great help for your collaboration.
Thanks, Have a great day.

Hi @iqra-s

You’ll have to delete new_query from this line:

so it becomes:

def handle_query_change():

This should now work. As the error message is telling us that the handle_query_change function is missing an input argument. But since you’re using it as a callback function with no arguments then it makes sense to delete as suggested previously.

Hope this helps!