Building Powerful Chatbots with ChatGPT API and Python | Part 01

Sunny Bhaveen Chandra
6 min readMar 13, 2023

--

Photo by Zac Wolff on Unsplash

Chatbots have revolutionized the way businesses interact with their customers. They allow companies to offer 24/7 customer service, provide instant responses to customer inquiries, and streamline their operations. With the rise of natural language processing (NLP), chatbots have become even more sophisticated and effective in their customer interactions. ChatGPT is one such NLP model that can be used to build powerful chatbots. In this article, we will explore how to use ChatGPT API using Python.

What is ChatGPT?

ChatGPT is an NLP model developed by OpenAI that is capable of generating human-like responses to text input. The model is based on the GPT (Generative Pretrained Transformer) architecture, which is a type of neural network that has been trained on a massive amount of text data to generate coherent and natural-sounding text.

The ChatGPT API allows developers to integrate the model into their applications and build chatbots that can engage in human-like conversations with users. The API provides a simple interface that can be used to send text input to the model and receive its response.

Setting up the environment

Open google colab. and create a new notebook [Refer to the screenshot below — ]

Google colab new notebook

Install this openai python package in the first cell of google colab by running the following command —

!pip install openai -q

Obtain the openai API keys -

STEP 1: Sign up
Signup at the official openai website — https://beta.openai.com/signup

NOTE: While signing up for the first time you will be asked for your contact no. if that contact no. is never been used to signup then you’ll get some free credits to use this API without getting charged. And to see your usage you can check https://platform.openai.com/account/usage after signing up.

STEP 2: Sign in
Sign in using the above credentials.

STEP 3: Create and save your API key as an environment variable or use it as a variable.
1. Go to your profile icon as shown in the following screenshot
2. Select View API keys

profile page of openai platform

3. Click on Create new secret key as shown in the following screenshot -

Create API key page for the openai platform

4. Now copy the API key generated and save it as an environment variable OPENAI_API_KEY or create a constant variable in your jupyter notebook for this demo

Generated key

Run the demo code:

In your Colab notebook proceed to copy and paste the code provided below, executing each code cell individually.

Note:

1. Explanation of the code follows.

2. Scroll the following codeblock to see the entire code or follow this link —chatGPT notebook

Code explanation:-

To use the API, we first need to authenticate ourselves using an API key. Setup openai API key in the following code block to make an authorized API call —

import openai
import os
openai.api_key = "YOUR_API_KEY"

Define the model engine name for chatGPT—

MODEL_NAME = "gpt-3.5-turbo" # Model used in chatGPT

Take user input for our first query —

OUR_QUES = input("Enter your Ques?: ")

Use ChatCompletion class from openai to ask queries from the chatGPT model. Pass model and messages in the following format —

# use ChatCompletion class from openai
response = openai.ChatCompletion.create(
model=MODEL_NAME,
messages=[
{"role": "user", "content": OUR_QUES} # role: user means we
]
)

response

Since we are asking the query hence role in the messages is defined as “user”

Now to get a proper outcome you can use the following code as the outcome of the response is in json format —

content = response['choices'][0]['message']['content']
print(content)

As the content from the above is a bot response, let’s use it to pass it on to our model to have some context of the previous question and ask the next question. And for that, we will again ask the user for a follow-up next question and pass on this content as a bot response —

OUR_NEXT_QUES = input("Enter your Next Ques?: ")

# to use the previous context we are using the previos response from the bot here
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": content}, # role: assistant means bot
{"role": "user", "content": OUR_NEXT_QUES} # out new question
]
)

response

In the above code, you can see that content is passed under the role “assistant” which refers to our model(bot).

Now use the following to print the outcome —

content = response['choices'][0]['message']['content']
print(content)

Following is our summary of chatting using chatGPT API —

HUMAN: Say something about hidden technical debt in ML

chatGPT BOT: Hidden technical debt in ML refers to the issues that are not visible in the models developed using machine learning algorithms. These can include data biases, poor data quality, or incorrect assumptions made during model building. Such issues can lead to poor performance, unreliable results, or incorrect decision-making. They can also be hard to detect as the models may appear to be functioning effectively, but the underlying issues can cause significant problems in the long run. The key to avoiding hidden technical debt in ML is to thoroughly test and validate the training data, and actively monitor the model’s performance to ensure it is producing accurate results.

HUMAN: Can you share the reference paper? for your content

chatGPT BOT: I can cite the following papers that discuss the concept of hidden technical debt in machine learning:

1. Sculley, D., Holt, G., Golovin, D., Davydov, E., Phillips, T., Ebner, D., … & Chaudhary, V. (2015). Hidden technical debt in machine learning systems. Google, 19(2015), 250–259.

2. Mitchell, M., Wu, S., Zaldivar, A., Barnes, P., & Vasserman, L. (2019). “Model Cards for Model Reporting.” Conference on Fairness, Accountability, and Transparency.

Both of these papers discuss the hidden technical debt in machine learning and suggest ways to mitigate it.

The preceding dialogue demonstrates the versatility of the chatGPT API in generating human-like conversations. To validate this claim, you may refer to the accurate citations provided in the second response.

Conclusion:

In this article, we have explored how to use the ChatGPT API using Python. Using ChatGPT API, developers can build powerful chatbots that can engage in human-like conversations with users, providing a more natural and intuitive user experience. With the rise of NLP and AI, chatbots are becoming an essential tool for businesses of all sizes, and ChatGPT is one of the most advanced and capable models available today.

References:

Additional resources:

[1] For setting up a complete environment for python projects:

[2] Playlist to create-test-publish python packages and more —

2

[3] My YouTube Channel for more — https://www.youtube.com/c17hawke

I hope these resources are helpful!

In the upcoming part 2 of this blog, we will construct a chatbot with a user interface to explore the same use case.

Till then keep on learning! and keep on exploring!!

--

--