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:
Implement ChatGPT in a Flask Application
Next article icon

Create a ChatBot with OpenAI and Gradio in Python

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

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 ChatGPT has developed a large model called GPT(Generative Pre-trained Transformer) to generate text, translate language, and write different types of creative content. In this article, we are using a framework called Gradio that makes it simple to develop web-based user interfaces for machine learning models. GPT-3-powered chatbots may be developed with Gradio.

This article will demonstrate how to use Python, OpenAI[ChatGPT], and Gradio to build a chatbot that can respond to user input.

Chatbot with Gradio - Chatgpt
 

Required Modules 

pip install openai
pip install gradio

Steps to create a ChatBot with OpenAI and Gradio in Python

Here we are going to see the steps to use OpenAI in Python with Gradio 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, gradio library, and then do as follows. Store the created key in the below-mentioned variable.

Python
import os import openai import gradio 

Step 5: Here we are getting the user chat history and storing it in a list and adding it to the previous state.

Python
def message_and_history(input, history):     history = history or []     print(history)     s = list(sum(history, ()))     print(s)     s.append(input)     print('#########################################')     print(s)     inp = ' '.join(s)     print(inp)     output = api_calling(inp)     history.append((input, output))     print('------------------')     print(history)     print(history)     print("*********************")     return history, history 

Step 6: Now we create the header for the gradio application and we are defining the gradio UI Submitting the input we are changing the current state of the Chatbot.

Python
block = gradio.Blocks(theme=gradio.themes.Monochrome()) with block:     gradio.Markdown("""<h1><center>ChatGPT ChatBot      with Gradio and OpenAI</center></h1>     """)     chatbot = gradio.Chatbot()     message = gradio.Textbox(placeholder=prompt)     state = gradio.State()     submit = gradio.Button("SEND")     submit.click(message_and_history,                   inputs=[message, state],                  outputs=[chatbot, state]) block.launch(debug = True) 

Complete Code :

Python
import os import openai import gradio openai.api_key = "YOUR_API_KEY" prompt = "Enter Your Query Here" 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 def message_and_history(input, history):     history = history or []     s = list(sum(history, ()))     s.append(input)     inp = ' '.join(s)     output = api_calling(inp)     history.append((input, output))     return history, history block = gradio.Blocks(theme=gradio.themes.Monochrome()) with block:     gradio.Markdown("""<h1><center>ChatGPT      ChatBot with Gradio and OpenAI</center></h1>     """)     chatbot = gradio.Chatbot()     message = gradio.Textbox(placeholder=prompt)     state = gradio.State()     submit = gradio.Button("SEND")     submit.click(message_and_history,                   inputs=[message, state],                   outputs=[chatbot, state]) block.launch(debug = True) 

Output:

Gradio Open AI
Gradio OpenAI

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 Gradio. 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
Implement ChatGPT in a Flask Application

A

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

Similar Reads

  • OpenAI Python API - Complete Guide
    OpenAI is the leading company in the field of AI. With the public release of software like ChatGPT, DALL-E, GPT-3, and Whisper, the company has taken the entire AI industry by storm. Everyone has incorporated ChatGPT to do their work more efficiently and those who failed to do so have lost their job
    15+ min read
  • Extract keywords from text with ChatGPT
    In this article, we will learn how to extract keywords from text with ChatGPT using Python. ChatGPT is developed by OpenAI. It is an extensive language model based on the GPT-3.5 architecture. It is a type of AI chatbot that can take input from users and generate solutions similar to humans. ChatGPT
    4 min read
  • Pandas AI: The Generative AI Python Library
    In the age of AI, many of our tasks have been automated especially after the launch of ChatGPT. One such tool that uses the power of ChatGPT to ease data manipulation task in Python is PandasAI. It leverages the power of ChatGPT to generate Python code and executes it. The output of the generated co
    9 min read
  • Text Manipulation using OpenAI
    Open AI is a leading organization in the field of Artificial Intelligence and Machine Learning, they have provided the developers with state-of-the-art innovations like ChatGPT, WhisperAI, DALL-E, and many more to work on the vast unstructured data available. For text manipulation, OpenAI has compil
    11 min read
  • OpenAI Whisper
    In today's time, data is available in many forms, like tables, images, text, audio, or video. We use this data to gain insights and make predictions for certain events using various machine learning and deep learning techniques. There are many techniques that help us work on tables, images, texts, a
    9 min read
  • Spam Classification using OpenAI
    The majority of people in today's society own a mobile phone, and they all frequently get communications (SMS/email) on their phones. But the key point is that some of the messages you get may be spam, with very few being genuine or important interactions. You may be tricked into providing your pers
    6 min read
  • How to Use chatgpt on Linux
    OpenAI has developed an AI-powered chatbot named `ChatGPT`, which is used by users to have their answers to questions and queries. One can access ChatGPT on searchingness easily. But some users want to access this chatbot on their Linux System. It can be accessed as a Desktop application on Ubuntu o
    6 min read
  • PandasAI Library from OpenAI
    We spend a lot of time editing, cleaning, and analyzing data using various methodologies in today's data-driven environment. Pandas is a well-known Python module that aids with data manipulation. It keeps data in structures known as dataframes and enables you to alter, clean up, or analyze data by c
    9 min read
  • ChatGPT Prompt to get Datasets for Machine Learning
    With the development of machine learning, access to high-quality datasets is becoming increasingly important. Datasets are crucial for assessing the accuracy and effectiveness of the final model, which is a prerequisite for any machine learning project. In this article, we'll learn how to use a Chat
    7 min read
  • How To Implement ChatGPT In Django
    Integrating ChatGPT into a Django application allows you to create dynamic and interactive chat interfaces. By following the steps outlined in this article, you can implement ChatGPT in your Django project and provide users with engaging conversational experiences. Experiment with different prompts,
    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