Personal ChatGPT Bot with Streamlit: Build Your AI Assistant Web app

Tattooed Geek
Nerd For Tech
Published in
9 min readJul 25, 2023

--

Do you want to have your very own AI-powered web-app that can understand your questions and provide helpful answers? Look no further! With the power of Python and Streamlit combined with OpenAI APIs, building a personalized ChatGPT bot is easier than you might think.

Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science. You can build and deploy powerful data apps in just a few minutes. So let’s get started!

Streamlit platform | Source: streamlit.io

To add more value and as a USP of my blog, I share this month’s bonus tip or best productivity tools that are cheap, effective, and a game changer, which I personally use and prefer. So do check them out and use them. Keep learning and growing.

Here is the Bonus tip for you all:

1) NOTION:

Bonus Tip 1: One great AI all-in-one Productivity/Task management tool I recently started using is Notion. Over the past few months, Notion has become famous and my absolute favorite.

If you’re like me, Juggling work, daily tasks, notes, and projects is tough. Multiple tabs for email, Slack, and Google Docs make it overwhelming. I personally use Notion AI, which streamlines everything in one place. It’s a game-changer, and you won’t regret using it.

I’ve been using its PRO version for a while now, and I must say, it’s been a complete game-changer for me. With almost every online co-working tool integration you can think of, it makes my daily work routine a breeze.

Plus, the pricing is unbeatable/cheapest for the tonnes of features it provides compared to all other all-in-one AI productivity tools I have used. I have taken up the annual subscription for mere 8$/month. Another awesome tool which is litreally dirt cheap.

I love its Web Clipper and use its Mac app, and I also use Notion on my phone. You can download the desktop app from here.

Do check out this cool post about Notion to know more about this brilliant platform.

Best all-in-one AI Productivity tool for this month

2)QUILLBOT:

Bonus Tip 2: One great AI Productivity Writing tool I recently started using for day-to-day writing and tasks such as plagiarism checker, grammar checker, Quillbot-Flow , paraphraser, summariser, and translator is QuillBot .

I wanted to try something similar and cheaper than Grammarly.

I took up its yearly premium for around $4/month(58 % off). The price is literally dirt cheap compared to other writing and prductivity AI tools I have used in the past.

Personally, it’s UI and UX is very simple and easy to use. So I just wanted to share this awesome, productive tool with you all. Do check it out and use it in your day-to-day writing tasks.

https://try.quillbot.com/

Best Productivity Writing tool for this month

Index

Introduction — The Power of Personal AI Assistants

Setting Up OpenAI API Key and Streamlit

Building the ChatGPT Bot with Streamlit

Running the ChatGPT Bot using Streamlit

Model Parameters for Customizing Responses

Making the WebApp Visually Appealing

Frequently Asked Questions (FAQs)

Conclusion

By the end of this post, you should be able to run a ChatGPTbot web app easily like the below:

Sample screenshot from the app

1. Introduction — The Power of Personal AI Assistants

Imagine having your AI-powered chatbot web app ready to answer questions, generate creative content, and assist you in your daily tasks. Thanks to OpenAI’s powerful language models and easy-to-use APIs, building a personal AI assistant is now within reach of any Python developer. This tutorial will show you how to create your ChatGPT bot using the Streamlit framework and OpenAI’s GPT-3.5-turbo model.

2. Setting Up OpenAI API and Streamlit

Before building the ChatGPT bot, ensure access to OpenAI’s API. You can sign up for an API key on the OpenAI website if you haven’t already. Once you have your API key, set it up as an environment variable in your development environment on the terminal/shell:

export OPENAI_API_KEY=<YOUR_API_KEY>

Next, install the required libraries and set up your Python environment:

pip install streamlit openai

3. Building the ChatGPT Bot with Streamlit

Let’s dive into the code to build our chatbot using Streamlit. Create a Python file (e.g., chatbot_app.py) and follow along:

import streamlit as st
import openai
import os

# Set your OpenAI API key here
openai.api_key = os.getenv("OPENAI_API_KEY")

# Function to interact with the GPT-3.5-turbo model with tunable parameters
def generate_response(prompt, temperature=0.7, max_tokens=256, top_p=0.9, n=2, stop=None, frequency_penalty=0.9, presence_penalty=0.9, chat_history=None):
if chat_history is None:
chat_history = []

messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt},
]
messages.extend(chat_history)

response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
top_p=top_p,
n=n,
stop=stop,
frequency_penalty=frequency_penalty,
presence_penalty=presence_penalty
)

return response['choices'][0]['message']['content']

# Streamlit app header and title
# tattooed geek logo
logo1 = 'https://miro.medium.com/v2/resize:fit:180/1*ypRBA86IBBbZbti76vm4Hg.png'
# Streamlit app header and title
st.set_page_config(page_title="Personal ChatGPT bot | By Anish Singh Walia", page_icon=logo1 , layout="wide")


st.write("# Personal Chatbot with GPT-3.5-turbo :sunglasses: ")
st.write("Made with love by - [Anish Singh Walia](https://anishsinghwalia.medium.com/)")
st.write("Welcome to your personal chatbot app! Type your message below:")


# Sidebar with social profiles and model parameters
st.sidebar.markdown("# Follow me on my Social Profiles")
st.sidebar.markdown(
"""<a href="https://github.com/anishsingh20" target="_blank"><img src="https://cdn-icons-png.flaticon.com/512/25/25231.png" alt="GitHub" width="60px"></a>
<a href="https://www.linkedin.com/in/anish-singh-walia-924529103/" target="_blank"><img src="https://cdn1.iconfinder.com/data/icons/logotypes/32/circle-linkedin-512.png" alt="LinkedIn" width="60px"></a>
<a href="https://medium.com/@anishsinghwalia" target="_blank"><img src="https://cdn1.iconfinder.com/data/icons/social-media-circle-7/512/Circled_Medium_svg5-512.png" alt="Medium" width="60px"></a>
<a href="https://instagram.com/cali_br20" target="_blank"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Instagram_logo_2016.svg/2048px-Instagram_logo_2016.svg.png" alt="Instagram" width="60px"></a>
""",
unsafe_allow_html=True,
)

# HTML sidebar to fine-tune model's parameters to customize the bot's responses.
st.sidebar.markdown("# Model Parameters")
temperature = st.sidebar.slider("Temperature", 0.0, 1.0, 0.7, 0.1)
max_tokens = st.sidebar.number_input("Max Tokens", 50, 500, 256, step=50)
top_p = st.sidebar.slider("Top P", 0.1, 1.0, 0.9, 0.1)
n = st.sidebar.number_input("N", 1, 5, 2, step=1)
stop = st.sidebar.text_input("Stop", "")
frequency_penalty = st.sidebar.slider("Frequency Penalty", 0.0, 1.0, 0.9, 0.1)
presence_penalty = st.sidebar.slider("Presence Penalty", 0.0, 1.0, 0.9, 0.1)

# Main app where user enters prompt and gets the response
user_input = st.text_area("You:", "", key="user_input")
generate_button = st.button("Generate Response")


# Chat history
messages = []
if user_input.strip() != "":
messages.append({"role": "user", "content": user_input})
response = generate_response(user_input, temperature, max_tokens, top_p, n, stop, frequency_penalty, presence_penalty)
messages.append({"role": "assistant", "content": response})

st.subheader("Chat History")
for message in messages:
if message["role"] == "user":
st.text_area("You:", value=message["content"], height=50, max_chars=200, key="user_history", disabled=True)
else:
st.text_area("Jarvis:", value=message["content"], height=500, key="chatbot_history")

# Additional styling to make the app visually appealing
st.markdown(
"""
<style>
body {
font-family: Montserrat, sans-serif;
}
.stTextInput>div>div>textarea {
background-color: #f0f0f0;
color: #000;
}
.stButton button {
background-color: #4CAF50;
color: white;
font-weight: bold;
}
.stTextArea>div>textarea {
resize: none;
}
.st-subheader {
margin-top: 20px;
font-size: 16px;
}
.stTextArea>div>div>textarea {
height: 100px;
}
</style>
""",
unsafe_allow_html=True,
)

In this code, we set up our Streamlit app with a header, title, and text input area where users can interact with the chatbot. We also create a sidebar with social profiles and model parameters that we can fine-tune to customize the bot’s responses.

  • Streamlit App Setup: In this part, we set up the Streamlit app’s user interface. We create a simple text area where users can type their messages, and a button to generate the AI’s response. We also provide sliders and text input fields for tuning the model parameters.
  • GPT-3.5-turbo Model Interaction: This part includes the function generate_response responsible for communicating with the GPT-3.5-turbo model through OpenAI's chatcompletion.create() API.

You can explore more about Streamlit’s documentation here.

4. Running the ChatGPT Bot using Streamlit

To run the ChatGPT bot, execute the following command in your terminal or command prompt:

streamlit run chatbot_app.py

This will launch the Streamlit app in your default web browser. You can now start interacting with your personal ChatGPT bot!

The deployed WebApp

5. Model Parameters for Customizing Responses

The GPT-3.5-turbo model allows us to adjust several parameters to control the chatbot's behavior. Here’s a brief explanation of each parameter:

Temperature: Controls the randomness of the responses. Higher values (e.g., 1.0) make the output more diverse, while lower values (e.g., 0.2) make it more focused and deterministic.

Max Tokens: Limits the length of the response generated by the model.

Top P: Specifies the cumulative probability threshold for choosing the next token. Higher values (e.g., 0.9) result in more focused responses.

N: Determines the number of different responses generated by the model, which helps in exploring different possibilities.

Stop: Allows us to specify a stopping phrase to indicate the end of the response.

Frequency Penalty: Controls the model’s likelihood of repeating the same response.

Presence Penalty: Controls how much the model considers using a token that hasn’t been mentioned in the conversation.

You can read more about fine-tuning model parameters here in my previous post on Model Parameters in OpenAI API

6. Making the App Visually Appealing

To make the app visually appealing, we have added some additional styling. The text area for the user’s input is set with a light gray background, and the chatbot’s responses are displayed in a larger text area. The button for generating the response is styled with a bold green color.

7. Frequently Asked Questions (FAQs)

Q1: What is the GPT-3.5-turbo model?

GPT-3.5-turbo is a highly advanced language model developed by OpenAI. It is designed to understand natural language and generate human-like text responses. With fewer tokens and lower costs than previous models, it provides an efficient and cost-effective solution for various AI applications.

Q2: Can I deploy this ChatGPT bot on Shell/terminal?

You can find a detailed guide on deploying your ChatGPT bot on shell/terminal in my previous article, Build and Deploy Your Personal Jarvis ChatGPT Bot in Python with ChatGPT API on MacOS.

Q3: Where can I learn more about model parameters in OpenAI API?

For a comprehensive understanding of model parameters and how they influence the behavior of language models, check out our article on Model Parameters in OpenAI API.

Q4: How can I ensure the security of my OpenAI API key?

To ensure the security of your OpenAI API key, follow the best practices outlined in my article Safeguarding Your AI: Best Practices for Securing Your OpenAI API Key.

8. Conclusion

Congratulations! You’ve successfully built your ChatGPT bot using the Streamlit framework and OpenAI’s GPT-3.5-turbo model. Now, you can interact with your AI assistant, customize its responses, and even deploy it on macOS or any other platform. Feel free to experiment with different model parameters to achieve the desired responses.

Please Subscribe and Follow to get Free access to my newsletter and keep yourself updated on the latest AI and ChatGPT trends and technologies to make your lives easier and more productive, save money, and be effective at whatever you do.

Your support motivates me to keep researching, designing cheatsheets, and writing about such topics.

Connect with me on GitHub and LinkedIn to stay updated with more exciting AI content, collaborate on projects, and build together.

Read the below blog post on how Generative AI + Streamlit is the best combination for AI developers and AI enthusiasts for developing and quickly deploying LLMs and complex generative AI applications over the web.

Github Repo for this project:

For more information on the OpenAI API and the GPT-3.5-turbo model, you can visit the OpenAI API documentation and the OpenAI platform.

Happy coding, and have fun exploring the possibilities of conversational AI!

--

--

Tattooed Geek
Nerd For Tech

Main-Blog:https://medium.com/@anishsingh20 / | Medium Top Writers(India) | Solopreneur | Founder@DataInksights | Medium 150,000+ views/70,000+ Reads - monthly