Create a ChatBot with OpenAI and Gradio in Python
Last Updated :
16 Apr, 2025
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.
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 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:
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