Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to use PyGWalker with Streamlit in Python
Next article icon

Create a ChatBot with OpenAI and Streamlit in Python

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Streamlit
OpenAI and Streamlit

Required 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') 
Streamlit OpenAI
Chat History

Complete 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
Streamlit OpenAI Output

Conclusion

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


Next Article
How to use PyGWalker with Streamlit in Python

A

ashutoshbkvau
Improve
Article Tags :
  • Python
  • Python-Streamlit-2
  • Python-Library
  • ChatGPT
Practice Tags :
  • python

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
  • Create Interactive Dashboard in Python using Streamlit
    An interactive and Informative dashboard is very necessary for better understanding our data sets. This will help a researcher for getting a better understanding of our results and after that, a researcher can make some necessary changes for better understanding. Visual Reports is must better than i
    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
  • 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 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences