Beginner's Guide: Building a Chatbot Front-End Using Python and Streamlit

Introduction

Chatbots are becoming an essential part of websites and applications, enhancing user engagement and automating customer service. In this guide, we will walk through the steps to create a simple chatbot front-end using Python and Streamlit. Streamlit is a powerful tool for creating interactive web applications with minimal effort.

Prerequisites

Before we begin, ensure you have the following installed on your machine:

  • Python 3.7 or later
  • Streamlit
  • OpenAI's GPT-3 or any chatbot API [optional]

Step 1: Setting Up the Project

First, create a new directory for your project and navigate into it. Then, create a new Python file named 'Chatbot.py', where we will write our Streamlit code. The command 'code' will open the new Python file in VS Code. If you don't have VS Code, you can use Notepad or any other text editor to create and edit the Python file.

**\GitHub> mkdir ChatBot-using-Streamlit
**\GitHub> cd ChatBot-using-Streamlit
**\GitHub\ChatBot-using-Streamlit> code Chatbot.py

Step 2: Importing Required Libraries

In your 'Chatbot.py' file, start by importing the necessary libraries:

import streamlit as st
# Initialize OpenAI API (Replace 'your-api-key' with your actual OpenAI API key)

import openai

openai.api_key = 'your-api-key'
For a dummy front-end application, we can temporarily disregard the API connection. We will use
'random' and 'time' libraries to simulate chatbot responses.

import random
import time

Step 3: Setting Title and Initializing Chat History

We set the title of the Streamlit application and initialize the chat history in the Streamlit session state.

# Set title for the application
st.title("Simple Bot")

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

Step 4: Setup dummy response generator

Next, let's set up a dummy response generator for our chatbot. While we can integrate any API to generate responses to user prompts, we'll start by building a simple 'response_generator' function. This function will simulate typing by yielding words one by one with a short delay, creating a more interactive and realistic user experience.

def response_generator():
    response = random.choice(
        [
            "Hello there! How can I assist you today?",
            "Hi, this chatbot is under development",
            "Sorry, I don't have information on that",
        ]
    )
    for word in response.split():
        yield word + " "
        time.sleep(0.05)

Step 5: Displaying Chat History

In the event of an app rerun, we want to ensure that chat messages are preserved. We will display the chat messages from the session history whenever the app is rerun.     

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

Step 6: Accepting user input and generating responses

We accept user input using 'st.chat_input' and display the user's message in the chat container. Then, we generate the assistant's response using 'response_generator' and display it in the chat container. Please note that you can plug in any API to provide a response to the user prompts. 

if prompt := st.chat_input("What is up?"):
    # Display user message in chat message container
    with st.chat_message("user"):
        st.markdown(prompt)
       
    # Add user message to chat history
    st.session_state.messages.append({"role": "user", "content": prompt})

    # Display assistant response in chat message container
    with st.chat_message("assistant"):
        response = st.write_stream(response_generator())
    # Add assistant response to chat history
    st.session_state.messages.append({"role": "assistant", "content": response})

In the code, we save each prompt and response to the session state, ensuring that the chat history is always stored and can be retrieved on subsequent app reruns.

Step 7: Running the Application

Save your 'Chatbot.py' file and run the Streamlit application using the following command in the terminal:

**\GitHub\ChatBot-using-Streamlit> streamlit run Chatbot.py

Open the URL provided by Streamlit in your web browser. You should see a simple chat interface where you can type messages and get responses from the chatbot.

Conclusion

Congratulations! You have successfully built a basic chatbot front-end using Python and Streamlit. This is a foundational project, and you can enhance it by adding features like better styling, prompt suggestions, more sophisticated conversation handling, or integrating different chatbot models. Streamlit makes it easy to build and deploy interactive applications, so feel free to experiment and expand your project.

Happy coding!

Comments

Popular posts from this blog

Beginner's Guide: Hosting Your HTML Static Site on GitHub

The Spark I Couldn't Find!

Feeling Down? These Korean Dramas Will Lift Your Spirits!