Streamlit Chatbot
Streamlit is a Python Framework for building interactive web apps with minimal code.
In this article, we will demonstrate how to use Streamlit to create a simple chatbot interface.
Need a streamlit developer: Click here
Our First minimal chatbot interface using Streamlit
This example will show how to create a basic chatbot interface using Streamlit.
We will use the `st.text_input()` function to get user input and display responses using `st.write()`.
import streamlit as st
st.set_page_config(page_title="Simple Chatbot", layout="wide")
st.title("Simple Chatbot Interface")
st.write("This is a basic chatbot interface built with Streamlit.")
user_input = st.text_input("You: ", placeholder="Type your message here...")
if user_input:
# Simulating a simple response from the chatbot
response = f"Chatbot: You said '{user_input}'"
st.write(response)

2 Adding history to the chatbot
We can enhance the chatbot by maintaining a history of the conversation.
This will allow users to see previous messages in the chat.
st.title("Chatbot with History")
st.write("This chatbot maintains a history of the conversation.")
if "messages" not in st.session_state:
st.session_state.messages = []
#Display chat history
for message in st.session_state.messages:
st.write(message)
# Get user input
with st.form("chat_form"):
user_input = st.text_input("You: ", placeholder="Type your message here...")
submit = st.form_submit_button("Send")
if submit and user_input:
st.session_state.messages.append(f"You: {user_input}")
bot_reply = f"I heard you say: {user_input}"
st.session_state.messages.append({"role": "Bot", "content": bot_reply})
st.session_state.input_box = ""
st.rerun()
# Rerun to update the chat history display

3 Styling the Chatbot Interface
We can further enhance the chatbot interface by adding some styling and layout features.
This will make the chatbot more visually appealing and user-friendly.
We can style with st.chat_message() to display messages in a chat-like format.
import streamlit as st
if "messages" not in st.session_state:
st.session_state.messages = []
st.title("Styled Chatbot Interface")
st.write("This chatbot uses Streamlit's chat message styling.")
# # Display chat history with styling
for message in st.session_state.messages:
if isinstance(message, str):
st.write(message)
if prompt := st.chat_input("Type your message:... "):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
bot_reply = f"Echo: {prompt}"
with st.chat_message("assistant"):
st.markdown(bot_reply)
st.session_state.messages.append({"role": "assistant", "content": bot_reply})


4 Adding Persistent Memory (Save/Load Chat History)
we can store chat logs in a file
import json
def save_history():
with open("history.json", "w") as f:
json.dump(st.session_state.messages, f)
def load_history():
try:
with open("history.json", "r") as f:
st.session_state.messages = json.load(f)
except FileNotFoundError:
st.session_state.messages = []
5 Adding Features
Clear chat button
if st.button("Clear Chat"):
st.session_state.messages = []
st.write("Chat cleared.")
Download chat s text
This download button allows users to download the chat history as a text file.
chat_text = "\n".join([f"{msg['role']}: {msg['content']}" for msg in st.session_state.messages])
st.download_button(
label="Download Chat as Text",
data=chat_text,
file_name="chat_history.txt",
mime="text/plain"
)
6 Integrating with OpenAi
We will create a chatbot that can respond to user queries using the OpenAI API.
This will allow us to leverage AI capabilities to provide intelligent responses.
Make sure you have the OpenAI Python package installed: `pip install openai`
Note: You need an OpenAI API key to use this feature.
import streamlit as st
import openai
openai.api_key ="your openai api key"
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = [{"role": "system", "content": "You are a helpful assistant"}]
st.title("💬 AI Chatbot (OpenAI 1.x)")
# Display chat history as chat bubbles
for msg in st.session_state.messages:
if msg["role"] != "system":
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
# Chat input
if prompt := st.chat_input("Type your message..."):
# Add user message
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Get OpenAI response
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=st.session_state.messages
)
bot_reply = response.choices[0].message.content
# Add assistant message
st.session_state.messages.append({"role": "assistant", "content": bot_reply})
with st.chat_message("assistant"):
st.markdown(bot_reply)
