DEV Community

Cover image for Streamlit Part 7: Build a Chat Interface
James
James

Posted on

Streamlit Part 7: Build a Chat Interface

Let's Build a Chat Interface in Streamlit: The Easy Way

Ever wanted to build your own chat interface but thought it would be too complicated? Well, I've got good news - with Streamlit, it's surprisingly simple. Let's walk through creating a basic chat app that you can later expand into something more sophisticated.

What We're Building

We're creating a chat interface where users can type messages and get responses. Think of it as the foundation for your future chatbot or AI assistant. The best part? You'll need just a few lines of Python code to make it happen.

Getting Started

First, let's set up our Streamlit app. We'll need a nice wide layout to give our chat messages plenty of room:

import streamlit as st  
import time  

st.set_page_config(  
    page_title="Chat App",  
    layout="wide",  
    initial_sidebar_state="collapsed",  
)  

st.title("Let's Chat!")  
Enter fullscreen mode Exit fullscreen mode

Keeping Track of Messages

Chat apps need memory - they need to remember what was said earlier in the conversation. Streamlit has a neat feature called session state that's perfect for this:

if "messages" not in st.session_state:  
    st.session_state.messages = []  
Enter fullscreen mode Exit fullscreen mode

This creates a list to store our chat history. Think of it as a notebook where we write down everything that's said.

Showing the Conversation

Now let's display our chat messages. We'll loop through our message history and show each message in a chat bubble:

for msg in st.session_state.messages:  
    with st.chat_message(msg["role"]):  
        st.write(msg["content"])  
Enter fullscreen mode Exit fullscreen mode

Getting User Input

Here's where the magic happens. We'll add a text box where users can type their messages:

prompt = st.chat_input("Say something...")  

if prompt:  
    # Add user message to chat  
    st.session_state.messages.append({"role": "user", "content": prompt})  
    with st.chat_message("user"):  
        st.write(prompt)  

    # Add a simple bot response  
    time.sleep(1)  # A brief pause to make it feel more natural  
    bot_response = f"You said: {prompt}"  
    st.session_state.messages.append({"role": "bot", "content": bot_response})  
    with st.chat_message("bot"):  
        st.write(bot_response)  
Enter fullscreen mode Exit fullscreen mode

Making It Your Own

Right now, our bot just echoes back what you say. But this is where you can get creative! You could:

  • Connect it to an AI model for smarter responses
  • Add buttons for quick replies
  • Include images or emojis in responses
  • Save conversations to a database

The Complete Code

Here's everything together in one neat package:

import streamlit as st  
import time  

st.set_page_config(page_title="Chat App", layout="wide", initial_sidebar_state="collapsed")  
st.title("Let's Chat!")  

if "messages" not in st.session_state:  
    st.session_state.messages = []  

for msg in st.session_state.messages:  
    with st.chat_message(msg["role"]):  
        st.write(msg["content"])  

prompt = st.chat_input("Say something...")  

if prompt:  
    st.session_state.messages.append({"role": "user", "content": prompt})  
    with st.chat_message("user"):  
        st.write(prompt)  

    time.sleep(1)  
    bot_response = f"You said: {prompt}"  
    st.session_state.messages.append({"role": "bot", "content": bot_response})  
    with st.chat_message("bot"):  
        st.write(bot_response)  
Enter fullscreen mode Exit fullscreen mode

And there you have it! A working chat interface in under 30 lines of code. Pretty cool, right?

Next time, we'll look at adding some AI smarts to make our bot actually understand and respond to messages. Stay tuned!

Want to try this out? Just copy the code, install Streamlit (pip install streamlit), and run it with streamlit run your_file.py. Happy coding!


🔗 Get the Code: GitHub - jamesbmour/blog_tutorials
🔗 Related Streamlit Tutorials:JustCodeIt
🍻 Support my work: Buy Me a Coffee

Top comments (0)