Streamlit that run analyze on submit and one of the result is a chat, when submitting a new message in chat i want to keep the result and not refresh
To upload files, please first save the app
import streamlit as st
import numpy as np
import pandas as pd
# Initialize states
if "analysis_done" not in st.session_state:
st.session_state.analysis_done = False
if "messages" not in st.session_state:
st.session_state.messages = []
if "analysis_results" not in st.session_state:
st.session_state.analysis_results = None
st.title("Analysis with Chat")
# Input form
with st.form("analysis_form"):
data_input = st.number_input("Enter a number for analysis", value=0)
submit_button = st.form_submit_button("Run Analysis")
if submit_button:
# Perform analysis
st.session_state.analysis_results = {
"square": data_input ** 2,
"sqrt": np.sqrt(data_input),
"log": np.log(data_input) if data_input > 0 else "undefined"
}
st.session_state.analysis_done = True
# Display analysis results if available
if st.session_state.analysis_done:
st.header("Analysis Results")
# Create columns for different metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Square", f"{st.session_state.analysis_results['square']:.2f}")
with col2:
st.metric("Square Root", f"{st.session_state.analysis_results['sqrt']:.2f}")
with col3:
st.metric("Natural Log", st.session_state.analysis_results['log'])
# Display chat interface
st.header("Discussion")
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
# Chat input
if prompt := st.chat_input("Discuss the results..."):
# Add user message
st.session_state.messages.append({"role": "user", "content": prompt})
# Add a simple assistant response
assistant_response = f"Thanks for your comment about the analysis. The square of your input was {st.session_state.analysis_results['square']:.2f}."
st.session_state.messages.append({"role": "assistant", "content": assistant_response})
# Rerun to display the new messages
st.rerun()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?