Build your custom chatbot using chatgpt

Vishnu Sivan
Coinmonks
Published in
12 min readMar 26, 2023

--

ChatGPT is the most powerful language model ever built. It is an amazing tool that can be used in various ways to enhance your productivity and learning. ChatGPT can supports for quick answers to trivial questions or in-depth explanations of complex concepts. ChatGPT has become a trending AI tool in just a matter of weeks. It hit 100 million monthly active users in last January, according to data from Similarweb.

According to Drift’s 2021 State of Conversational Marketing report, 74% of companies want to implement conversational Artificial Intelligence (AI) tools to streamline workflow. It is clear that it has wide range of applications from customer service to virtual assistants. ChatGPT is a well-suited example as it can generate human-like responses to user inputs.

In this article, we will learn more about ChatGPT and build a custom chatbot using python and react frameworks.

Getting Started

Table of contents

What is ChatGPT

ChatGPT was created by OpenAI, a research company co-founded by Elon Musk and Sam Altman. The company launched ChatGPT on Nov. 30, 2022. It is one of the most sophisticated language processing AI models with 175 billion parameters.

ChatGPT can generate anything with a language structure, which includes answering questions, writing essays and poetry, translating languages, summarizing long texts, and even writing code snippets!

ChatGPT uses state of the art AI techniques to understand and generate human-like responses to a wide range of questions and prompts. It uses a combination of natural language processing techniques and machine learning algorithms to understand the meaning behind words and sentences and to generate responses that are appropriate to the context of the conversation. It has been trained on a massive corpus of text data, including articles, books, and websites, enabling it to provide precise and insightful answers.

How to use ChatGPT

You can access ChatGPT by visiting chat.openai.com, creating an OpenAI account and agreeing to chatGPT terms.

  • Create an OpenAI account
    Go to chat.openai.com and register for an account with an email address. You need to create an account on the OpenAI website to log in and access ChatGPT.
  • Accept ChatGPT terms
    Once you logged into your OpenAI account on the website, go through the terms and conditions for ChatGPT and click on Next. Click on Done to finish it.
  • Start writing prompts
    ChatGPT is ready to use now. You can type in any prompts in the textbox at the bottom of the page and press enter to submit it. The AI chatbot will then provide helpful answers to your prompts.

You can put any of the example prompts mentioned in the site or your own one to get the answer. The result for Explain quantum computing in simple terms looks like below,

GPT3 integration in Python

The OpenAI Python library provides convenient access to the OpenAI API from applications written in the Python language.

Follow the below steps to integrate GPT3 in python.

  • An API token is required to access OpenAI’s services.
  • Open platform.openai.com.
  • Click on your name or icon option which is located on the top right corner of the page and select “API Keys” or click on the link — Account API Keys — OpenAI API
  • Click on create new secret key button to create a new openai key.
  • Create and switch to a virtual environment before installing dependencies for openai and other libraries.
python -m venv venv
source venv/bin/activate # for linux
venv\Scripts\activate # for windows
  • Install the OpenAI Python library using pip.
pip install openai
  • Create a new python file chatgpt_demo.py and add the following code to it.
import openai
openai.api_key = "" # your token goes here

def get_model_reply(query, context=[]):
# combines the new question with a previous context
context += [query]

# given the most recent context (4096 characters)
# continue the text up to 2048 tokens ~ 8192 charaters
completion = openai.Completion.create(
engine='text-davinci-002',
prompt='\n\n'.join(context)[:4096],
max_tokens = 2048,
temperature = 0.4, # Lower values make responses more deterministic
)

# append response to context
response = completion.choices[0].text.strip('\n')
context += [response]

# list of (user, bot) responses. We will use this format later
responses = [(u,b) for u,b in zip(context[::2], context[1::2])]

return responses, context

query = 'Which is the largest country by area in the world?'
responses, context = get_model_reply(query, context=[])

print('<USER> ' + responses[-1][0])
print('<BOT> ' + responses[-1][1])
  • Run the script using the following command,
python chatgpt_demo.py

openai.Completion.create() gives you the GPT3 response based on your query. In the above example, we asked it to explain what quantum computing in single terms. It was able to come up with a sharp answer to the query.

Gradio based frontend creation

Gradio is an open-source Python library used to build AI related web applications. It allows developers to create user-friendly and customizable interfaces.

Follow the below steps to create gradio based frontend for displaying the content.

  • Install the gradio python library using pip.
pip install gradio
  • Add the following code to the chatgpt_demo.py file.
import gradio as gr

# defines a basic dialog interface using Gradio
with gr.Blocks() as dialog_app:
chatbot = gr.Chatbot()
state = gr.State([])

with gr.Row():
txt = gr.Textbox(
show_label=False,
placeholder="Enter text and press enter"
).style(container=False)

txt.submit(get_model_reply, [txt, state], [chatbot, state])

# launches the app in a new local port
dialog_app.launch()
  • Run the app using the following command,
python chatgpt_demo.py

Gradio will open a new port and launch an interactive app when dialog_app.launch() is executed. Running the examples provided in the previous section should return the same expected results. Messages entered by the user will appear on the right-hand side, while messages generated by OpenAI will be displayed on the left-hand side.

Build a custom chatbot

In this section, we will create a custom chatbot using GPT3 with python as the backend and react as the frontend.

1.1 Create a data file

The first step is to create a data file which contains the information about a specific topic. In this example, we use a quantum physics related content. Scrap the data from the link — scienceexchange quantum-physics and add it inside a text file named data.txt under the data folder.

Ensure that you have added the below text as a prefix in the data.txt file.

I am VBot, your personal assistant. I can answer questions based on general knowledge.

Answer questions based on the passage given below.

The final data file looks as below,

1.2 Create the environment

Create and switch to a virtual environment before installing dependencies for openai and other libraries.

python -m venv venv
source venv/bin/activate # for linux
venv\Scripts\activate # for windows

1.3 Install dependencies

Install the openai, fastapi, uvicorn, itsdangerous and python-dotenv libraries using pip.

pip install openai fastapi uvicorn itsdangerous python-dotenv

1.4 Create environment (.env) file

Create a file named .env and add environment variables for openai api key and secret key to it.

export OPENAI_API_KEY="openai-key"
export SECRET_KEY="32-length-random-text"

1.5 Openai GPT3 backend integration

Create a new file main.py and add the following code to integrate the Openai GPT3 model for your query responses.

Understand the code:

  • Load the environment variables and set the openai.api_key.
  • Create a method read_file(file) to read the contents from the text file.
  • Initialize session_prompt variable with the data file content using the read_file method. Also, initialize start_sequence and restart_sequence values as “\nVBot:” and “\n\nUser:”
  • Create a method answer(ques, chat_log). It takes questions and chat log as arguments and provides response from the openai with the help of openai.Completion.create() method.
  • message_check() and checkViolation() methods are responsible for verifying the openai requests and responses using the openai.Moderation.create() method.
  • gpt3_logs method specifies the openai requests and responses in a predefined format.

1.6 Create and integrate a fastapi server

Create an api server to make the gpt3 integration available via http requests. For which, fastapi is selected to create apis.

Create a file named app.py and add the following code to it.

Understand the code:

  • Import fastapi library methods and middlewares. Create a basic fastapi object app as app = FastAPI().
  • Load the environment file and add the secret key inside the fastapi middleware. Configure the middleware with CORS.
  • Create a get route “/” which will send a response as “Hit from VBot”.
  • Create a get route “/api/response” which will receive a request from the user and send it to the main() method and send the response back to the user if the response is non-empty.
  • Run the uvicorn server using uvicorn.run(“app:app”,port = 8000,reload=True).

1.7 Run backend server

  • Run the backend python server using the following command.
python app.py

2.1 Create the frontend app

Create a react application using create-react-app cli.

npx create-react-app chatbot-frontend

2.2 Install Tailwind CSS

  • Install tailwindcss and generate tailwind.config.js file using npm.
npm install -D tailwindcss
npx tailwindcss init
  • Add the following code to the tailwind.config.js file.
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
  • Add the @tailwind directives to the top of the ./src/index.css file.
@tailwind base;
@tailwind components;
@tailwind utilities;

2.3 Install dependencies

Install react-speech-recognition,axios and react-loader-spinner packages to the app using the following command.

npm i react-speech-recognition axios react-loader-spinner

2.4 Create bot frontend

Add the following code to the App.js file.

Understand the code:

  • Import assets (bg, arrow, mic, mic_on icons), axios, speech recognition and dna (react loader spinner) packages.
  • Initialize states such as userInput, recording, loading and messages. userInput is used to keep the user inputs, recording collects user input from the mic and messages stores the request / response from the bot.
  • The useEffect hook (line no 50–69) calls the backend api (http://localhost:8000/api/response?message=userInput) with user input and stores the responses from the bot in the messages state.
  • The sendMessage() sets the user input inside the messages state if the user input is not empty. This action calls the useEffect() method where the message state added in the dependency array.
  • The handleRecording() method handles the user voice input and stores it in the userInput state.
  • Lines from 97 to 150 sets the UI with a user input text box, audio input icon, send button and message bubbles.
  • The UI accept the user input in the text box as text from console or through the speech recognition module. The userInput state updates on each key press. When the user clicks on the send button, it calls the sendMessage() method and it will set the messages state with userInput value if userInput is not empty. The messages values changes will call the useEffect() and send a request to the backend (http://localhost:8000). The response from the backend will be updated to the messages state with fromUser attribute as false. This value will be displayed on the message bubble as the bot response.

2.5 Run the app

  • Follow step 1.7 to run the backend server.
  • Run the frontend react app using the following command.
npm start

You will get the output as below,

There you have it! Your own chatbot powered by GPT3 :)

Applications of ChatGPT

ChatGPT is an amazing tool that can be used to enhance your productivity and learning. Let’s explore some of the ways you can use this tool to make your life easier and more productive.

  • Generate ideas and brainstorm
    ChatGPT can be beneficial for brainstorming ideas such as a birthday party celebration idea, recipe ideas or entire meal plans.
  • Understand complicated topics
    ChatGPT can give you precise, clear overviews on complex topics in layman’s terms. If you want to understand machine learning, or find out how quantum computing is being used, ChatGPT is the perfect choice to assist you to understand the topics.
  • Get assistance with coding and debugging
    ChatGPT can provide code examples, or help you troubleshoot by providing solutions to common coding issues or errors. It can also help you to look up syntax and parameters.
  • Train ChatGPT on your own data
    You can feed your own data into the model, and fine-tune the parameters of the model with algorithms. ChatGPT will be trained on your specific data. Finally, you can export the model and develop APIs that allow your system to interact with other tools and platforms.
  • As a writing assistant
    Whether it’s a poem, a news article, an email, or an essay, ChatGPT will provide customized content that you can use in different scenarios.
  • Get personalized recommendations
    ChatGPT can act as your shopping assistant, health assistant that provides you with customized recommendations to suit your tasks.
  • Summarize the latest research
    ChatGPT can summarize research works including entire reports, web pages, or studies. It will provide summarize content of your prompt.
  • Translate text
    It is a powerful tool to translate a text into different languages. It supports 95 different languages.
  • Find data sets
    ChatGPT is useful for looking for datasets, it can search through various online databases, repositories, and resources to find relevant data sets for you. You can use the feature for research, business intelligence, or for training a machine learning model.
  • Sentiment Analysis
    ChatGPT can analyze the words, phrases, and punctuation used in the text and determine the tone of it such as positive, negative, or neutral.

Thanks for reading this article.

Thanks Gowri M Bhatt for reviewing the content.

Thanks Fabius S Thottappilly and Grigary C Antony for the support in creating a custom chatbot using ChatGPT.

If you enjoyed this article, please click on the clap button 👏 and share to help others find it!

The article is also available on Dev.

If you are interested to develop chatbot using Rasa then checkout the following article,

The full source code for this tutorial can be found here,

Useful links:

--

--

Coinmonks
Coinmonks

Published in Coinmonks

Coinmonks is a non-profit Crypto Educational Publication. Other Project — https://coincodecap.com/ & Email — gaurav@coincodecap.com

Vishnu Sivan
Vishnu Sivan

Written by Vishnu Sivan

Try not to become a man of SUCCESS but rather try to become a man of VALUE

Responses (4)