The Wayback Machine - https://web.archive.org/web/20240924183524/https://www.geeksforgeeks.org/create-a-chatbot-with-openai-and-gradio-in-python/
Open In App

Create a ChatBot with OpenAI and Gradio in Python

Last Updated : 24 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python3




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.

Python3




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.

Python3




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 :

Python3




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:



Previous Article
Next Article

Similar Reads

Create a ChatBot with OpenAI and Streamlit in Python
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. Required Modules pip install openaip
5 min read
Sam Altman fired as CEO by OpenAI board - Who is the New CEO of OpenAI?
In a surprising turn of events, OpenAI, the creator of ChatGPT, made a major announcement on Friday regarding significant shifts in its leadership structure. The company revealed a notable shakeup in its top positions, removing Co-founder and current CEO, Sam Altman, from his role. The board's decision also led to the repositioning of the current C
6 min read
Glucose Test Values Interpreter GUI Using Gradio in Python
This article is going to create a basic GUI using the Python package Gradio to interpret Glucose Test Values to infer appropriate results. Gradio is an open-source library that helps programmers effortlessly create User Interface(UI) components for functions with just a few lines of code.Given the glucose test values of a patient in mg/dl, the task
3 min read
How to Create a ChatBot Application using ChatGPT API in Flutter?
A ChatBot is a computer program that uses Artificial Intelligence (AI) and Natural Language Processing (NLP) to understand customers' questions and give responses to them simulating human behavior. Building our own ChatBot from scratch requires us to train the Machine Learning (ML) model with rigorous amounts of text-based data, providing it with d
11 min read
OpenAI’s GPT Store Launched! How to Use and Make Money
OpenAI, a leading player in the field of artificial intelligence, has launched its much-anticipated GPT Store. This innovative platform allows users to find useful and popular custom versions of ChatGPT, the company’s flagship chatbot product. ChatGPT is powered by GPTs, which are specialized language models that can be created and customized by an
7 min read
OpenAI ChatGPT 5 Launch: Release date, Upgrades, Pricing and Everything Else
The world of Artificial Intelligence is abuzz with anticipation for the upcoming launch of OpenAI's ChatGPT 5. This next-generation language model promises to be a big step forward, pushing the boundaries of human-machine interaction and artificial intelligence capabilities. While the exact ChatGPT 5 release date remains unconfirmed, rumours and sp
6 min read
What is OpenAI SearchGPT? How it works and How to Get it?
OpenAI, the company behind the popular ChatGPT AI assistant, has announced the launch of its own search engine called SearchGPT. This highly anticipated move positions OpenAI as a potential rival to established search giants like Google and Bing. OpenAI SearchGPT is a cutting-edge search engine optimization (SEO) tool powered by artificial intellig
8 min read
Level up your ChatGPT Game with OpenAI's Free Course on Prompt Engineering for Developers
Want to learn Prompt Engineering? OpenAI made it possible for you! The parent company of ChatGPT launched a free ChatGPT course on prompt engineering for developers. An interesting new course on prompt engineering called "ChatGPT Prompt Engineering for Developers" has been curated by renowned artificial intelligence (AI) experts Andrew Ng from Deep
3 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 carrying out various operations like generating a b
10 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 compiled a Completions model which helps you to generate
11 min read
Develop an LLM Application using Openai
Language Models (LMs) play a crucial role in natural language processing applications, enabling the development of tools that generate human-like text. OpenAI's Generative Pre-Trained Transformer (GPT) models, such as GPT-3.5-turbo, are widely used in this domain. They excel in understanding context, learning language patterns, and generating coher
5 min read
OpenAI’s Sam Altman’s Most Used App
In the world of artificial intelligence, few names are as prominent as Sam Altman, the CEO of OpenAI. Known for his leadership in one of the most innovative AI companies in the world, Altman is a figure who constantly pushes the boundaries of technology. However, a recent revelation about his most used app has left many surprised. During a conversa
2 min read
OpenAI Codex vs. GitHub Copilot: Which AI Assists Programmers More Effectively?
What if developing a game was as easy as writing a command like "bounce an object" in plain English? You could manipulate digital objects in any way you wanted, without any programming knowledge whatsoever. Thanks to text-to-code models like OpenAI Codex, this dream isn't that far away anymore. As OpenAI has already demonstrated, non-technical user
6 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, and videos, but there are not a lot of techniques t
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 personal information, such as your password, account n
6 min read
OpenAI Launches GPT-4o Omni
OpenAI has announced its latest innovation, "GPT 4o Omni," a free and significantly faster version of its predecessor, GPT 4. This advanced language model builds on the success of GPT 4 including the ability to understand and respond to information across multiple modalities—text, speech, and images. This "omnimodal" capability means a substantial
4 min read
OpenAI tests ChatGPT widget for Android Home Screen - Check how to Use it
OpenAI has introduced a game-changing widget for its widely-used chatbot, ChatGPT, specifically designed for Android smartphones. This innovative feature empowers users to interact with ChatGPT directly from their home screens, eliminating the need to launch the app itself. This signifies a significant step forward in user experience and accessibil
5 min read
Google Gemini AI vs OpenAI ChatGPT: Everything to Know About It
The field of AI has seen surprising breakthroughs in recent years, with the advancement of strong generative models that can compose text, pictures, and different kinds of content based on natural language inputs. Two of the most prominent instances of such models are Google Gemini and OpenAI ChatGPT, which compete for the title of the most develop
8 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 algorithms to generates a variety of responses. It m
4 min read
Deploy a Chatbot using TensorFlow in Python
In this article, you'll learn how to deploy a Chatbot using Tensorflow. A Chatbot is basically a bot (a program) that talks and responds to various questions just like a human would. We'll be using a number of Python modules to do this. This article is divided into two sections: First, we'll train the Chatbot model, and then in section two, we'll l
9 min read
Dominos Chatbot using Python
Chatbots are gaining popularity as a means for businesses to interact with their customers. Domino's Pizza is one such company that has used a chatbot to improve its customer service. In this article, we'll look at how to use Python to create a chatbot for Domino's Pizza. Tools and Technologies Used: The chatbot for Domino's Pizza will be built usi
11 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 a chatbot that would be capable of answering most
4 min read
Simple Chatbot application using Python, GoogleAPIKey
Google-GenerativeAI is Google AI Python SDK. It uses Gemini to build AI-powered features. In this article, we will see how to create a Simple Chatbot application using Python GoogleAPIKey. What is Google-GenerativeAI?Google-GenerativeAI is nothing but Google AI Python SDK. It enables to use of Gemini to build AI-powered features and applications. T
4 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 town AI chatbot. Baidu’s Ernie AI chatbot is also con
6 min read
Battle of AI Chatbots: Which ChatBot Will Rule the Present and Future?
Do you know how many days Facebook and Instagram took to reach a 1 million user audience? Well, around 2 to 3 months! Incredible growth speed, right? Now let’s see how many days does AI chatbot ChatGPT took to hit the 1 million user count – 5 days! That’s how popular AI chatbots are! As we move towards the AI-influenced future, lots of AI chatbots
6 min read
Talking Healthcare Chatbot using Deep Learning
Today in this article we are going to see how we can build a Talking Healthcare Chatbot using Deep Learning. It is recommended to know the basics of Deep Learning, the Intermediate stage of knowing Python, and the Theory of Neural Networks. Users should also be familiar with how to use the SpeechRecognition module and set it up. First, we need to i
14 min read
Google BARD AI: How to Use the AI Chatbot?
After being originally introduced to the public, ChatGPT has advanced web search technology. Users started switching to ChatGPT when it stunned the most widely used search engine in the world, Google, with its straightforward search technique. Being one of the largest companies, Google also introduced its own AI chatbot BARD in the ChatGPT competit
8 min read
Chinese Company Tencent is About to Launch ChatGPT-Like AI Chatbot
Tencent Holding the prominent Chinese company known for its social media and video gaming ventures, is gearing up to unveil its latest artificial intelligence (AI) foundation model named "Hunyuan." This exciting launch is set to take place at an upcoming event scheduled for Thursday. Its entry into the competitive arena of large language models (LL
5 min read
ChatGPT Plus vs. Perplexity: Which Is the Better AI Chatbot?
In the rapidly evolving landscape of AI chatbots, the competition between ChatGPT Plus and Perplexity has garnered significant attention. As businesses and individuals seek advanced conversational solutions, understanding the distinctions between these two platforms becomes crucial. Let's delve into a comparative analysis of ChatGPT Plus and Perple
6 min read
Grok AI – AI Chatbot With a Sense of Humour (New ChatGPT Alternative)
Elon Musk, the founder of xAI, has launched Grok AI, a clever chatbot with humor, something missing in competitors like AI Chatbot ChatGPT and BARD. Let's see what makes Grok different and how it stacks up against these other chatbots. Developed under Musk's direction, Grok gives users a unique experience, offering engaging conversations filled wit
8 min read
Practice Tags :