chat feature which also plots plotly
To upload files, please first save the app
import streamlit as st
import random
import time
import plotly.express as px
# Streamed response emulator
def response_generator():
response = random.choice(
[
"Hello! How can I assist you with plotting today?",
"Hi! Do you want me to create a plot for you?",
"What kind of data visualization would you like?",
]
)
for word in response.split():
yield word + " "
time.sleep(0.2)
st.title("Chat and Plotly Interface")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"):
st.markdown(message["content")
# Accept user input
if prompt := st.chat_input("What would you like to plot?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Example of generating and displaying a plot
if "plot" in prompt.lower():
# Sample data for plot
df = px.data.iris()
fig = px.scatter(
df,
x="sepal_width",
y="sepal_length",
color="species",
size="petal_length",
hover_data=["petal_width"],
)
# Display the plot
with st.chat_message("assistant"):
st.plotly_chart(fig, use_container_width=True)
response_content = "Here is the plot you requested!"
else:
with st.chat_message("assistant"):
response_content = "I can only create plots. Please specify a plot request."
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response_content})
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?