Building a Chatbot with ChatGPT

Introduction

Chatbots are gaining traction in today's digital world, as they offer a range of benefits, including customer service, lead generation, and virtual assistance. In this article, we will explain how to build a chatbot using ChatGPT, a language model developed by OpenAI that is capable of generating natural language responses to prompts and questions.

An Overview of ChatGPT

ChatGPT is a large language model that utilises the GPT-3.5 architecture developed by OpenAI. It is designed to facilitate natural language processing and can generate responses to prompts and questions, making it a suitable tool for creating chatbots. In this article, we have chosen the GPT-3.5 turbo model which has proved to be faster and more capable.

Prerequisites

Python

To build a chatbot with ChatGPT API, you you will need to install the Python programming language on your computer.

Download link: https://www.python.org/downloads/

Getting your OpenAI API key

To use ChatGPT in your chatbot, you will need an OpenAI API key. Here's how to get one:

  1. Go to the OpenAI website at https://platform.openai.com/.
  2. Enter your email address and password to create an account.
  3. Follow the instructions to verify your email address and complete your account setup.
  4. Once you're logged in, click on your username in the top right corner of the page and select "Dashboard" from the dropdown menu.
  5. Click on the "API Keys" tab in the left-hand menu.
  6. Click on the "Generate New Key" button.
  7. Give your API key a name and click "Generate Key".
  8. Copy your API key to a safe location (such as a password manager) and keep it confidential.

Once you have your API key, you can use it to authenticate your requests to the OpenAI API and access the ChatGPT model. Remember to keep your API key confidential and secure to prevent unauthorised access to your account.

Setting Up the Chatbot

To start, create a new project in your desired programming language. For this tutorial, we will be using Python. You will also need to install the openai library.

Open a terminal (linux or macos users) or a command prompt (windows users). Then install the openai library by running the following command:

pip install openai

For those who already installed the OpenAi library in the past, you should update using the following command:

pip install --upgrade openai

Building the chatbot

Once you have installed the openai module and obtained your API key, you can set up the ChatGPT API in your Python code. First, import the openai module and set your API key:

import openai
openai.api_key = "YOUR API KEY"

Next, define the model_engine variable to specify which version of the GPT-3 model you want to use. In this example, we will use the "gpt-3.5-turbo" model:

model_engine = "gpt-3.5-turbo"

Now that we have set up the ChatGPT API, we can define the generate_response() function to get a response from the API. The function takes a prompt as input and returns the response from the chatbot:

def generate_response(prompt):
    response = openai.ChatCompletion.create(
        model=model_engine,
        messages=[{"role": "user", "content": prompt }]
    )
    return response['choices'][0]['text']

Here's a breakdown of the function:

  • The openai.ChatCompletion.create() method sends a prompt to the ChatGPT API and returns a response.
  • The model parameter specifies which version of the GPT-3 model to use.
  • The messages parameter is a list of dictionaries that specify the role of the message (user or bot) and the content of the message.
  • The response variable stores the response from the API.
  • The return statement returns the text of the first choice in the response.

Running the chatbot

With the generate_response() function defined, we can now use it in the main program to run the chatbot. The program prompts the user for input, sends the input to the generate_response() function, and prints the response from the chatbot:

#main program
while True:
    prompt=str(input("\tYou: "))
    if prompt=="exit": #write exit to exit the program
        break
    try:
        response=generate_response(prompt)
        print("\nChatGPT: {0}".format(response))
    except Exception as e:
        print(e)
        print("Error: {0}".format(e))
        continue

Here's a breakdown of the main program:

  • The while loop runs indefinitely until the user types "exit".
  • The prompt variable stores the user's input.
  • The if statement checks if the user typed "exit", and if so, breaks out of the loop.
  • The try-except block calls the generate_response() function and stores the response in the response variable.
  • The print() statement

Final Script

import openai
openai.api_key = "YOUR OPENAI_API_KEY"
model_engine = "gpt-3.5-turbo"

#function to get the response from ChatGPT API
def generate_response(prompt):
    response = openai.ChatCompletion.create(
        model=model_engine,
        messages=[{"role": "user", "content": prompt }]
    )
    return response['choices'][0]['message']['content']

#main program
while True:
    prompt=str(input("\tYou: "))
    if prompt=="exit": #write exit to exit the program
        break
    try:
        response=generate_response(prompt)
        print("\nChatGPT: {0}".format(response))
    except Exception as e:
        print(e)
        print("Error: {0}".format(e))
        continue

print("End")


Conclusion

In this article, we have learned how to build a chatbot using the ChatGPT API and Python. With the power of OpenAI's language model, we can create chatbots that provide accurate and efficient responses to user queries. This technology has the potential to transform the way we interact with digital systems and revolutionise the field of education.


Links

Learn the coding skills to
advance your career !