The Future of Chatbots: Building a State-of-the-Art Stateless Chatbot with OpenAI's GPT and Streamlit

The Future of Chatbots: Building a State-of-the-Art Stateless Chatbot with OpenAI's GPT and Streamlit

Build a Memoryless Chatbot with Streamlit and OpenAI

Hello Humans 👋,
I recently created a memoryless or stateless chatbot using OpenAI's GPT & Id love to How I used GPT in my code and created a web app using Streamlit🎈.

Introduction

I developed a chatbot called 'Rumi GPT'.

How does it work?

Simply enter how you are feeling right now, and it will give you a beautiful quote by Rumi to help motivate and inspire you 😇. Whether you're looking for guidance, comfort, or just a pick-me-up, Rumi GPT has you covered. With Rumi GPT, you can find motivation and inspiration to uplift your day and help you achieve your goals.

Motivation

Why Rumi?

When I initially joined Twitter, I was unsure of whom to follow. I finally decided to follow accounts that tweet about books and motivational quotes. That was the day when I stumbled upon the work of Rumi. One of his quotes, in particular, captivated me and has held a special place in my heart ever since -

"Set your life on fire. Seek those who fan your flames."

Since then, I have delved deeper into Rumi's life and work, including his journey through Elif Shafak's masterpiece, "Forty Rules Of Love." Rumi's work has touched the lives of countless individuals over the centuries, and it is not difficult to see why. His poetry and philosophy inspire us to seek beauty in our lives, embrace love, and let go of our fears and doubts.

If you are not familiar with Rumi, here is some brief information about him:

Rumi was a 13th-century Persian poet, Islamic scholar, and Sufi mystic whose works have gained worldwide recognition and popularity. He is regarded as one of the greatest spiritual masters and poets in Islamic culture, known for his mesmerizing and insightful poetry that touches on themes of love, spirituality, and the human experience. People follow his work because of his profound insights, captivating language, and timeless relevance to the human condition, inspiring generations of readers and seekers to explore the depths of spirituality and the nature of existence.

How I built it using OpenAI's GPT?

Setup

To work with GPT you need to create an account on OpenAI. Simply head over to OpenAI's site and create an account. If you want to use any service of OpenAI, you have to use the API key. To create your API key go to https://platform.openai.com/

Go to 'View API keys'

Click on 'Create new secret key' if you don't have a secret key or you forgot to write it down somewhere.

After creating a Create new secret key, a new pop-up window will appear. Make sure to copy that secret key and write it down on a piece of paper and keep it safe in a bank locker.

Always keep your API key hidden from others. Here are a few guidelines from OpenAI.

https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety

Open your IDE or Google colab or anything that you prefer.

Now install openai and streamlit by using the following commands.

! pip install openai
! pip install streamlit

Once the download is completed, import them

import streamlit as st
import openai

I used a .toml file to safely hide my API key. Just simply create a .toml file and write your API key in it by assigning it to a variable. In python code, you can call it easily and your API key won't show up in the code. I saved my API key to a variable called "api_secret" and called it into the python file using the following code.

openai.api_key = st.secrets["api_secret"]

Following is the code that will help you to use GPT in python.

import openai
openai.api_key = "YOUR_API_KEY"

prompt = "Once upon a time" #Whatever you want to ask
model = "text-davinci-002" #model
max_tokens = 50

response = openai.Completion.create(
    engine=model,
    prompt=prompt,
    max_tokens=max_tokens
)

print(response.choices[0].text)

I did some modifications here and there to create a memoryless chatbot.

What is a memoryless chatbot?

A memoryless chatbot, also known as a stateless chatbot, is a type of conversational agent that does not store any data or context from previous interactions with the user. Unlike memory-based chatbots, which rely on user history to personalize their responses, memoryless chatbots treat each interaction as a new and independent request.

I created a function called get_rumi_quote() using the above code.

def get_rumi_quote(user_input):
    prompt = f"Give me a Rumi quote for : {user_input} and explain that quote. \n"
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=prompt,
        temperature=0.5,
        max_tokens=1024,
        n=1,
        stop=None,
        timeout=30,
    )
    message = response.choices[0].text
    return message

This piece of code gives a Rumi quote with little explanation about that quote. Yesterday OpenAI Launched a new GPT 3.5 turbo model, which is better than "text-davinci-002".

Web app using Streamlit 🎈

Streamlit is the easiest way to build a web app if you are a Machine Learning engineer who is now aware of Web Development.

To build a Streamlit app I used their documentation which is very well written.

I mean just look at this, who wouldn't want to learn Streamlit with this attractive representation?

Let's start with building the app!

def main():
    import streamlit as st
    st.image("Header_image.png") 

    html_temp = """
                    <div style="background-color:{};padding:1px">
                    </div>
                    """
    with st.sidebar:
        st.markdown("""
        # About 
        Hi!👋 I'm a chatbot that provides Rumi quotes to help motivate and inspire you 😇        """)
        st.markdown(html_temp.format("rgba(55, 53, 47, 0.16)"), unsafe_allow_html=True)
        st.markdown("""
        # How does it work
        Simply enter how you are feeling right now.
        """)
        st.markdown(html_temp.format("rgba(55, 53, 47, 0.16)"), unsafe_allow_html=True)
        st.markdown("""
        Made by [@Obelisk_1531](https://twitter.com/Obelisk_1531)
        """,
                    unsafe_allow_html=True,
                    )

    st.markdown("<h4 style='text-align: center;'>Let Rumi guide you with our chatbot🤖❤️ ️</h4>",
                unsafe_allow_html=True)

    user_input = st.text_input("\nTell me how you feel?\n")
    st.write("\n")

    st.markdown(
        """
        <style>
        .stButton button {
            background-color: #752400;
            color: white;
            border-radius: 4px;
            padding: 0.5rem 1rem;
            font-size: 1.25rem;
            margin: 0 auto;
            display: block;
        }
        </style>
        """,
        unsafe_allow_html=True,
    )

    st.button("Generate")

    if user_input:
        with st.spinner("I'm searching the best Rumi quote for you..."):
            quote = get_rumi_quote(user_input)
            st.write(f"\nHere's a Rumi quote for you: \n{quote}")

Streamlit functions I used are:

  1. st.image() to insert header image.

  2. st.sidebar:

  1. st.markdown : You can use the power of Markdown in the web app.

  2. st.text_input displays a single-line text string.

  3. st.write write arguments to the app, here I used it to go to the new line.

  4. st.button displays a widget button. In the above image, you can the button 'Generate'

  5. st.spinner temporarily displays a message while executing a block of code.

That's all the functions I used from Streamlit to build a web app. I used a little HTML as well to give the app a little touch-up. If you want to know how I deployed it on Streamlit cloud let me know in the comments below.

You can check out the app here Rumi-GPT

Link to the repository: Rumi_GPT

If you like my work, you can support me here: Support my work

I do welcome constructive criticism and alternative viewpoints. If you have any thoughts or feedback on our analysis, please feel free to share them in the comments section below.

Thank you for reading 😁.

For more such content make sure to subscribe to my Newsletter here

Follow me on

Twitter

GitHub

Linkedin

Did you find this article valuable?

Support Kaushal Powar by becoming a sponsor. Any amount is appreciated!