Create a ChatBot with OpenAI and Streamlit in Python
Last Updated :
16 Apr, 2025
ChatGPT is an advanced chatbot built on the powerful GPT-3.5 language model developed by OpenAI.There are numerous Python Modules and today we will be discussing Streamlit and OpenAI Python API to create a chatbot in Python streamlit. The user can input his/her query to the chatbot and it will send the response.
OpenAI and StreamlitRequired Modules
pip install openai
pip install streamlit
pip install streamlit-chat
Steps to create a ChatBot with OpenAI and Streamlit in Python
Here we are going to see the steps to use OpenAI in Python with Streamlit to create a chatbot.
Step 1: Log in to your OpenAI account after creating one.
Step 2: As shown in the figure below, after logging in, select Personal from the top-right menu, and then select "View API keys".
Step 3: After completing step 2, a page containing API keys is displayed, and the button "Create new secret key" is visible. A secret key is generated when you click on that, copy it and save it somewhere else because it will be needed in further steps.
Step 4: Import the openai,streamlit, and streamlit_chat library, and then do as follows. Store the created key in the below-mentioned variable.
python
import streamlit as st
import openai
from streamlit_chat import message
openai.api_key = 'API_KEY'
Step 5: Now we define a function to generate a response from ChatGPT using the "create" endpoint of OpenAI.
Python
def api_calling(prompt):
completions = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
message = completions.choices[0].text
return message
Step 6: Now we create the header for the streamlit application and we are defining the user_input and openai_response in the session_state.
Python
st.title("ChatGPT ChatBot With Streamlit and OpenAI")
if 'user_input' not in st.session_state:
st.session_state['user_input'] = []
if 'openai_response' not in st.session_state:
st.session_state['openai_response'] = []
def get_text():
input_text = st.text_input("write here", key="input")
return input_text
user_input = get_text()
if user_input:
output = api_calling(user_input)
output = output.lstrip("\n")
# Store the output
st.session_state.openai_response.append(user_input)
st.session_state.user_input.append(output)
Step 7: Here we are using the message functions to show the previous chat of the user on the right side and the chatbot response on the left side. It shows the latest chat first. The query input by the user is shown with a different avatar.
Python
message_history = st.empty()
if st.session_state['user_input']:
for i in range(len(st.session_state['user_input']) - 1, -1, -1):
# This function displays user input
message(st.session_state["user_input"][i],
key=str(i), avatar_style="icons")
# This function displays OpenAI response
message(st.session_state['openai_response'][i],
avatar_style="miniavs", is_user=True
, key=str(i) + 'data_by_user')
Chat HistoryComplete Code :
Python
import streamlit as st
import openai
from streamlit_chat import message
openai.api_key = "YOUR_API_KEY"
def api_calling(prompt):
completions = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
message = completions.choices[0].text
return message
st.title("ChatGPT ChatBot With Streamlit and OpenAI")
if 'user_input' not in st.session_state:
st.session_state['user_input'] = []
if 'openai_response' not in st.session_state:
st.session_state['openai_response'] = []
def get_text():
input_text = st.text_input("write here", key="input")
return input_text
user_input = get_text()
if user_input:
output = api_calling(user_input)
output = output.lstrip("\n")
# Store the output
st.session_state.openai_response.append(user_input)
st.session_state.user_input.append(output)
message_history = st.empty()
if st.session_state['user_input']:
for i in range(len(st.session_state['user_input']) - 1, -1, -1):
# This function displays user input
message(st.session_state["user_input"][i],
key=str(i),avatar_style="icons")
# This function displays OpenAI response
message(st.session_state['openai_response'][i],
avatar_style="miniavs",is_user=True,
key=str(i) + 'data_by_user')
Output:
Streamlit OpenAI OutputConclusion
We covered several steps in the whole article for creating a chatbot with ChatGPT API using Python which would definitely help you in successfully achieving the chatbot creation in Streamlit. There are countless uses of Chat GPT of which some we are aware and some we aren’t.
To learn more about Chat GPT, you can refer to:
Generate Images With OpenAI in Python
How to Use ChatGPT API in Python?
ChatGPT vs Google BARD – Top Differences That You Should Know
Similar Reads
Create a ChatBot with OpenAI and Gradio in Python
Computer programs known as chatbots may mimic human users in communication. They are frequently employed in customer service settings where they may assist clients by responding to their inquiries. The usage of chatbots for entertainment, such as gameplay or storytelling, is also possible. OpenAI Ch
3 min read
Python - Making a Reddit bot with PRAW
Reddit is a network of communities based on peopleâs interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them. A Reddit bot is something that automatically responds to a userâs post or automatically posts things at
2 min read
What is Ernie AI Chatbot and How it is Rivaling ChatGPT?
You are living under a rock if you havenât heard of ChatGPT yet! OpenAIâs chatbot ChatGPT has been making it into the tech-world highlights for quite a long now. Many experts are saying that ChatGPT will be revolutionizing the way we work! However, do you know? ChatGPT isnât the only talk of the tow
6 min read
How to use PyGWalker with Streamlit in Python
Streamlit is an open-source Python library that allows developers to create beautiful, interactive web applications for data science and machine learning projects with ease. PyGWalker (Python Graphic Walker) is an innovative data visualization tool that combines the simplicity of Python with the pow
3 min read
Build an AI Chatbot in Python using Cohere API
A chatbot is a technology that is made to mimic human-user communication. It makes use of machine learning, natural language processing (NLP), and artificial intelligence (AI) techniques to comprehend and react in a conversational way to user inquiries or cues. In this article, we will be developing
4 min read
Chat Bot in Python with ChatterBot Module
Nobody likes to be alone always, but sometimes loneliness could be a better medicine to hunch the thirst for a peaceful environment. Even during such lonely quarantines, we may ignore humans but not humanoids. Yes, if you have guessed this article for a chatbot, then you have cracked it right. We wo
3 min read
Create a Telegram Bot using Python
In this article, we are going to see how to create a telegram bot using Python. In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in
6 min read
How to Make an Instagram Bot With Python and InstaBot?
In this article, we are going to see how to make an Instagram bot using Python and InstaBot. Bots are really common these days to send messages, upload photos, send wishes, and many more things. Bots reduce our work, save time. Today we are creating an Instagram bot that can do the following things.
4 min read
Diabetes Prediction Machine Learning Project Using Python Streamlit
In this article, we will demonstrate how to create a Diabetes Prediction Machine Learning Project using Python and Streamlit. Our primary objective is to build a user-friendly graphical interface using Streamlit, allowing users to input data for diabetes prediction. To achieve this, we will leverage
3 min read
How to Make a Chatbot in Python using Chatterbot Module?
A ChatBot is basically a computer program that conducts conversation between a user and a computer through auditory or textual methods. It works as a real-world conversational partner. ChatterBot is a library in python which generates a response to user input. It used a number of machine learning al
4 min read