Hi,
I’m trying to build a chatbot that is having an option to display predefined example questions, or the questions provided by the user and be in Paused State if not doing anything. I’m getting my data and everything displayed. But my chat prompt is displaying multiple times. I’m attaching my code as well as the screenshots of what I’m getting, It’d be great if anyone could help.
`# Function to reset the password input field
def reset_password_field():
st.session_state.password = ""
# Check if the user is authenticated
if "authenticated" not in st.session_state:
st.session_state.authenticated = False
# Check if the user is authenticated
if not st.session_state.authenticated:
st.title("Authentication Required")
password = st.text_input("Please enter the password:", type="password", value=st.session_state.get("password", ""))
st.session_state.password = password
if st.button("Authenticate"):
if authenticate(password):
st.session_state.authenticated = True
st.success("Authentication successful!")
else:
st.error("Authentication failed. Please try again.")
image_path = "./Consult-Logo.png"
image = Image.open(image_path)
st.image(image, use_column_width=False, width=200)
# Create a Streamlit sidebar
st.sidebar.title("App Instructions")
# Add directions on how to use the app
st.sidebar.markdown("1. Enter your password to authenticate.")
st.sidebar.markdown("2. Use the chat interface to interact with the chatbot.")
st.sidebar.markdown("3. Ask questions on Push Notifications, SMS, Emails")
st.sidebar.markdown("4. Once the Query is generated, modify the query if needed and hit Run Query button.")
def reset_conversation():
st.session_state.messages = []
st.session_state.agent = create_agent()
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
if "agent" not in st.session_state:
st.session_state.agent = create_agent()
st.title("PivotConsult KFC Data Chatbot")
col1, col2 = st.columns([3, 1])
with col2:
st.button("Reset Chat", on_click=reset_conversation)
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
if message["role"] == "assistant":
if isinstance(message["content"], pd.DataFrame):
st.table(message["content"])
else:
st.markdown(message["content"])
else:
st.markdown(message["content"])
if "current_query" not in st.session_state:
st.session_state.current_query = ""
if "updated_query" not in st.session_state:
st.session_state.updated_query = ""
def change_query():
st.session_state.current_query = st.session_state.updated_query
# Accept user input
examples = [
" ",
"How was CLM performance yesterday?",
"How was CLM performance this Wednesday?",
"Which part of day has highest sessions for push notification yesterday?",
"What were opens on Wednesday for SMS CHANNEL?",
]
option = st.radio("Choose an option:", ("Select from examples", "Enter custom question", "Paused State"), index=2)
if option == "Select from examples":
selected_example = st.selectbox("Select an example:", examples, key="selected_example")
if selected_example and selected_example != " ":
prompt = selected_example
else:
prompt = ""
elif option == "Enter custom question":
prompt = st.text_input("Please enter your question:")
elif option == "Paused State":
st.warning("Code flow paused. Please make a selection to continue.")
st.stop()
else:
st.warning("Please select a valid option.")
if st.session_state.authenticated and option!='Paused State' and prompt:
with st.chat_message("user"):
st.markdown(prompt)
st.session_state.messages.append({"role": "user", "content": prompt})
query = return_query_with_ai(prompt)
st.session_state.updated_query = query
# Display user message in chat message container\]
option = ''
with st.chat_message("user"):
if option!= '':
st.markdown(prompt)
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
query = return_query_with_ai(prompt)
st.session_state.updated_query = query
# Display the generated SQL query
if st.session_state.authenticated and prompt:
st.text_area("Generated SQL Query:", key="updated_query", value=st.session_state.updated_query, on_change=change_query, height=200)
st.session_state.updated_query
# Execute the SQL query when the "Run Query" button is clicked
if st.session_state.authenticated and st.button("Run Query"):
run_query = st.session_state.get("updated_query", "") # Define query_editable here
if run_query.strip(): # Check if query_editable is not empty
print('button_clicked')
with st.spinner("Running query..."):
try:
print('Calling raw_query()')
result_data = get_data_from_query(run_query) # Execute the query and return as DataFrame#print(result_data.shape)
with st.chat_message("assistant"):
if isinstance(result_data, pd.DataFrame):
st.table(result_data) # Display the result as a table
else:
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}")
else:
st.error("Please enter a valid SQL query before running.")`
Screenshots:
Step1, select any option:
Step 2, You’ll be getting a resulting query, then Click ‘Run Query’
Step3, You’ll get the result table displayed after running the query, but you can see that there is extra empty chat prompt is there
Step4, I’m selecting a different question this time,
Step 5, Now the queries are getting removed from the UI and there is only prompt and the resulting table left for the previously asked question and the previous prompt is repeating 4 times, as you can see in the below screenshot.
Help me fix this. Thanks to everyone for interacting.
Regards,
Iqra