Learn OpenAI Official ChatGPT API: Comprehensive Developer Tutorial (AI 2023)

In this tutorial, we will provide high quality Python examples of OpenAI’s API using the openai Python library. We will also demonstrate ChatGPT API’s parameters to showcase its true powers and demonstrate some of the use cases of ChatGPT API with advance prompts which you’ve probably never anywhere else.

OpenAI models are quite hot topic right now. OpenAI has a very useful API structure which you can access with Python and leverage this edge-cutting modern technology.

This tutorial is a comprehensive guide about ChatGPT and covers quite a few areas including the brief history of ChatGPT and other complimentary information such as serialization of ChatGPT API responses with Python. If want to see the Python demonstration of ChatGPT API, you can skip to the middle parts where it says Learn ChatGPT API.

What is ChatGPT?

ChatGPT is an artificial intelligence (AI) technology designed to help people have natural conversations with computers. It uses a combination of natural language processing and machine learning algorithms to generate responses that are tailored to the user’s input. ChatGPT is able to understand the context of a conversation, recognize patterns in the user’s input, and generate meaningful responses. This makes it possible for users to have more realistic conversations with computers.

ChatGPT can also be used for applications such as customer service, virtual assistants, chatbots, 0and more. By using ChatGPT, companies can reduce customer service costs while providing better experiences for their customers. The technology is also becoming increasingly popular among developers who want to create AI-powered applications that provide real-time interaction with users.

How to use ChatGPT API

ChatGPT is an advanced language model created by OpenAI, capable of generating human-like responses to text-based inputs, that enables natural conversations between humans and machines. Developers can now integrate ChatGPT into their applications by using ChatGPT API, which is a REST API that can be accessed through code written in various programming languages including Python.

To start creating scripts and apps, you will first need an api key which can be acquired with an account from OpenAI. In this beginner’s guide we will provide high quality guidance using Python and walk you through the basic steps to understand and master the new chatgpt language model.

The API allows developers to create custom applications or scripts that interact with ChatGPT, generating responses to inputs that align with their specific objectives. By leveraging ChatGPT API, developers can create interactive chatbots, language processing tools, virtual assistants, and customer service applications that deliver human-like responses, enhancing the user experience and improving customer satisfaction.

Who is ChatGPT's founder? History of ChatGPT

When we look at the invention of ChatGPT, we see textbook description of flag race involving many successful individuals from diverse backgrounds, big tech companies, universities and influential tech leaders.

ChatGPT stands for Conversational Generative Pre-training Transformer. It is one of the many AI models that is based on the Transformer architecture introduced by Google AI Research.

ChatGPT made a big splash in the headlines so you might be wondering who its founder is or who developed the model that powers ChatGPT. So, let’s put things on perspective.

YEAR 2017: Additionally, ChatGPT is based on the BERT model which was introduced by the paper published by Google AI Research in 2017.

You can access the groundbreaking Attention is All You Need NLP research paper which was published in 2017 via the link. Transformer NLP architecture is a significant breakthrough in AI research and many impressive Natural Language Processing models are based on this architecture introduced by Google Researchers.

YEAR 2020: These researchers contributed to the ChatGPT model particularly. Preceding model before chatgpt (gpt-3.5-turbo) was gpt-3 which was introduced by the research paper Language Models are Few-Shot Learners. GPT3 model scaled GPT2 which was based on Transformers and involved 1.5 billion parameters.
 
YEAR 2021: Training neural network AI models using GPU clusters was introduced by Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM. This enabled scaling of AI parameters like never seen before in history.
 
YEAR 2022: It’s also important to mention that the training of OpenAI’s gpt-3.5 models took place (based on the GPU clustering suggested in 2021) on supercomputers provided by Microsoft Research and their cloud branch Azure. Additionally, highly specialized GPUs were manufactured by Nvidia.
 
We can see that the leading big tech companies, hardware companies, many successful AI researchers and influential tech entrepreneurs were involved, although many of them are competitors in other projects, in the journey that led to the creation of ChatGPT and the model it’s based on gpt-3.5.
 
The lists below are not exhaustive.

Transformers by Google

Transformer NLP architecture introduced by Google Researchers below:

  • Ashish Vaswani
  • Noam Shazeer
  • Niki Parmar
  • Jakob Uszkoreit
  • Llion Jones
  • Aidan N. Gomez
  • Lukasz Kaiser
  • Illia Polosukhin

GPT models
by OpenAI

ChatGPT is founded by OpenAI. OpenAI was founded by entities below:

  • Sam Altman,
  • Greg Brockman,
  • Reid Hoffman,
  • Jessica Livingston,
  • Peter Thiel,
  • Elon Musk,
  • Olivier Grabias,
  • Amazon’s AWS,
  • Infosys, and
  • YC Research

ChatGPT by Collective Effort

At OpenAI, following individuals have mainly created ChatGPT (gtp-3.5) based on gpt3.

  • Alec Radford,
  • Jeff Wu,
  • Prafulla Dhariwal,
  • Dario Amodei

Infrastructure used for training ChatGPT involved:

  • Azure supercomputer
  • 10K Nvidia GPUs
  • 285K Intel/AMD  cores
These researchers contributed to the ChatGPT model particularly.
Preceding model before chatgpt (gpt-3.5-turbo) was gpt-3 which was introduced by the research paper Language Models are Few-Shot Learners. GPT3 model scaled GPT2 which was based on Transformers and involved 1.5 billion parameters.
 
It’s also important to mention that the training of gpt-3.5 models took place on supercomputers provided by Microsoft Research and their cloud branch Azure. Additionally, highly specialized GPUs and CPUs were manufactured by Nvidia and Intel.
 
We can see that the leading big tech companies, hardware companies, many successful AI researchers and influential tech entrepreneurs were involved, although many of them are competitors in other projects, in the journey that led to the creation of ChatGPT and the model it’s based on gpt-3.5.

Future of AI & AGI

ChatGPT’s language processing capabilities and natural language understanding proficiency is like no other AI model before which triggered many discussions that we might be closer to AIG (Artificial General Intelligence) than we previously thought.

 
In scholar publication titled When Will AI Exceed Human Performance? Evidence from AI Experts Katja Grace et al. shared below finding.
 
Researchers believe there is a 50% chance of AI outperforming humans in all tasks in 45 years and of automating all human jobs in 120 years.
This study above was done in 2018, another AI survey by University of Oxford & MIRI had 738 expert participants where it was estimated that:
 
The aggregate forecast time to a 50% chance of HLMI (High Level Machine Intelligence) was 37 years, (*Year 2059)
 
And it will be interesting to see similar research from a more recent date. Let’s start learning Python code to create ChatGPT scripts with Python using the step-by-step tutorial below.

4- Learn ChatGPT API with Python

openai Python Library

We need the openai library to make API calls to ChatGPT with Python. openai library can easily be installed via using pip install command.

OpenAI Account for API key

You also need to sign up to OpenAI developer platform to get an account through which you can generate an OpenaAI API key. OpenAI offers a free account with $5 credit which you can use to learn and test its latest gpt model ChatGPT as well as previous gpt models.
 
We expect gpt-3.5-turbo to get a lot more use than other models since it is more advanced and it comes with 10x cheaper price per token. You can see more about ChatGPT API pricing in below section.
You can sign up here.

OpenAI API Authorization

After sorting out the openai library in your computer environment, next step is to establish an authorized connection to ChatGPT API. This can be achieved using openai.api_key combined with the API key you’ve acquired from OpenAI’s developer platform.
 
Here is an example:
import openai

OPENAI_API_KEY = 'YOUR_OPENAI_KEY'
openai.api_key = OPENAI_API_KEY

Python code above will provide the necessary API key to the openai library after which we can proceed with making automated API calls to the ChatGPT API Endpoint.

If you’re missing the library in your system it can be installed using pip commands. Just type:
 

pip install openai

Basic Python Example: ChatGPT Chat Completion
messages=[{"role": "user", "content": "Write a tagline for a Python platform."}]

response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", 
messages = message)

print(response)
ChatGPT API Output:

Unlock the power of code with Python – your all-in-one platform for limitless possibilities.

I think the result is quite impressive. This really is a powerful tagline that can be used on a Python learning platform such as Holypython.com.

ChatGTP API ChatCompletion Parameters

ChatCompletion is the function we have used to make API calls to ChatGPT model gpt-3.5-turbo above using Python. This function has some useful parameters which we can make use of when developing ChatGPT apps or scripts. The parameters that struck me as most useful initially are below:

model

  • model: This is pretty much mandatory as we need to specify gpt-3.5-turbo to access the ChatGPT model. There are many other AI models available from OpenAI platform. You can print a full list by following this Python tutorial.
    • Author’s model note: ChatGPT specific there is currently only one model which is gpt-3.5-turbo-0301, so gpt-3.5-turbo defaults to the same thing. In the near future, we expect many new variations of gpt-3.5 due to its extremely high popularity and usage frequency. By specifying the models you can increase the stability of your program or opt-in for specific models based on your or your users’ preference.

messages

  • messages: Also a mandatory parameter as we need to prompt ChatGPT with a message before it returns a response. After this parameter, you can use the following parameters as needed. So far I always make use of limit.
    • Author’s messages note: This parameter has extreme significance because now you can use the system prompt to instruct ChatGPT before responding to chat queries. This is similar to saying “Assume you are a crazy scientist.” in the web interface of ChatGPT which in most cases don’t register anymore and the model occasionally throws the cringy “I am just an AI model” response. Using the system prompt you can instruct ChatGPT quite freely and still bypass the default messages.

max_tokens

  • max_tokens: (optional) This parameter is incredibly useful not only because I want to spend my OpenAI API tokens wisely, but also sometimes I just want to limit the response of ChatGPT to certain token/word count size.
    • Author’s max_tokens note: This saves lots of time as the responses are returned in condensed format resulting in savings of time resources as well as funds. It’s infinite (inf) by default so it’s quite wise to make use of it in API calls. Infinite will still be limited by the model’s upper limit, in ChatGPT model it is 4096 tokens.
    • While using the ChatGPT web interface you might have prompt hacked this feature by specifying the sentence amount of the response or using adjectives like “briefly”, “in short” and “shortly”. One, too often they don’t work too well since it’s a subjective approach and two adjectives are too vague to achieve exact numerical outcomes. max_tokens works perfectly and saves time and money. I almost always use it even in personal Python scripts.

n

  • n: (optional) Parameter n must be an integer and it gives you the option to generate n number of responses from ChatGPT. Also very useful, it is 1 by default.
    • Author’s n note: n is certainly very useful in cases where multi-generation is needed. Instead of explicitly mentioning something like: “create 5 sentences of ….” desired outcomes can be achieved using the n parameter which is going to be more efficient and programmatic.

user

  • user: user parameter allows creation of a unique identifier for the end-user. This can help OpenAI identify abusive users which may be helpful for you if you are developing a service for many people.
    • Author’s user note: This one is mostly for OpenAI’s backend. However, in a scenario where your application generates millions of calls it can be a life saver since the calls will be compartmentalized. In cases of rogue users, instead of maybe introducing penalties to the whole account it would be used to filter specific bad actors in OpenAI’s system.

logit_bias

  • logit_bias: Using logit_bias, you can control the likeliness of a token’s appearance in the response. This parameter can be used to ban or force the appearance of words/tokens. The value limits are -100 to 100 and default is null. logit_bias parameter takes a json object where keys are integers (positions of tokens) and values are values between -100 and 100.
    • Author’s logit_bias note: This is great for creating nuanced applications and having a higher level of control in the response in terms of token occurrence. logit_bias can also be used to add an extra security layer where certain words are banned in the application from ever appearing in the ChatGPT responses.

temperature

  • temperature: Another great parameter temperature can be used to set the focus degree of the ChatGPT model. This is also called temperature sampling. While the parameter defaults to 1, it can take vales between 0 and 2. 0 will make the model exercise full focus while 2 will introduce great amount of randomness in the response.
    • Author’s temperature note: I particularly like this parameter because approaching 0 can be very useful where the response is required to be highly focused to the subject at hand. Additionally I also enjoy the scenarios where values between 1 and 2 are used to introduce increased randomness to the response. High response is very useful in terms of exploring the subject or potential responses to a question.

top_p

  • top_p: This parameter can be used for nucleus sampling. The meaning of that is tokens are evaluated by their probability values and tokens with less probability mass can be eliminated from the results. It is 1 by default and a value such as 0.5 would exclude 50% of the tokens from the pool based on their probability mass.
    • Author’s top_p note: OpenAI advises the usage of temperature or top_p mutually exclusively in general since they have somewhat similar impacts in the results. So if you choose to use temperature then you shouldn’t use top_p and vice versa. There might still be highly specialized cases where top_p and temperature are used together in harmony.

stop

  • stop: This parameter can be used to stop response generation. When the stop string or sequence (up to 4) is encountered ai model will stop generating tokens.
    • Author’s stop note: It is useful if you don’t want to continue after specific tokens which can be punctuation, words or word groups.

presence_penalty

  • presence_penalty: this optional penalty parameter defaults to 0 and it can take values between -2.0 and 2.0. If it’s a positive value new tokens will be penalized based on whether they appear in the text before.
    • Author’s presence_penalty note: This is extremely useful and it will make the language model mention new topics more likely. If the value is negative new tokens will be penalized if they haven’t appeared in the text before making the model stick to the same topic.

frequency_penalty

  • frequency_penalty: This parameter similarly defaults to 0 and it can take values between  -2.0 and 2.0. Penalization of new tokens takes place not only based on their presence before but also the frequency of presence. A positive value will decrease the likeliness of repeat tokens. A negative value is likely to cause word repetition.
    • Author’s frequency_penalty note: It’s a sophisticated argument to control the verbatim of ai model’s response to the prompts. Using the OpenAI Playground, the effects of these parameters can be studied and quickly understood.
2nd Python Example: ChatGPT n parameter

Let’s use the n parameter to run the prompt 3 times with ChatGPT. We will ask ChatGPT to print the best motivational quote ever.

We are also using the system role this time to make ChatGPT behave like an executive assistant.

Please note: This code is neglecting the authorization part with the api key. You can see the authorization section above.

import openai

messages=[
{"role": "system", "content": "You are a highly intelligent  executive assistant."},
{"role": "user", "content": "Print the best motivational quote ever."}]

response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages = messages, max_tokens=50, n=3, temperature= 1)
#print(response)

for i in response['choices']:
	print(i['message']['content'])

And the results below.

"Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle."
- Christian D. Larson

"The future belongs to those who believe in the beauty of their dreams"
- Eleanor Roosevelt.

"What you get by achieving your goals is not as important as what you become by achieving your goals."
- Zig Ziglar.

Wow. These are actually really profound and impressive quotes. I had never seen them before. I really like the 2nd and the 3rd quotes.

RestAPI technology with Python.

There were Python wrappers developed by the community but they didn’t work well and there were many complications due to authorization issues. Now we have the Official ChatGPT API released by the company behind the AI model, OpenAI.

RestAPI technology enables various types of software systems to communicate with one another. Python programming language can automate the process of building and implementing a RestAPI service.

RestAPI services in Python can be built to interact with a multitude of APIs such as ChatGPT API or OpenAI API, and these APIs can be leveraged to perform queries for a specific task. Python’s strong libraries and frameworks facilitate the development of RestAPIs very efficiently.

The automation of RestAPIs provides faster turnaround times on services, which in turn can increase the efficiency of the overall system. In this way, integrating RestAPI technology with Python programming is a powerful tool for improving the quality and consistency of many software systems.

When we use the openai library, it queries the API Endpoint for ChatGPT model which is https://api.openai.com/v1/completions.

If you are interested in RestAPI technology, we have a beginner level Python API Lesson.

3rd Python Example: ChatGPT temperature + system role

In this example, we can adjust a few parameters to optimize the responses we get from ChatGPT API. For example, temperature is useful to change focus level and system role can be assigned to make ChatGPT respond in specific tone and language. We will also make use of max_tokens to limit the length of the response.

  1. temperature: Let’s play with the temperature parameter. We will assign it a value of 0.1 first (highly focused) and then 1.7 (highly random). Both results are impressive and they demonstrate the extended usefulness and versatility of ChatGPT not only to interact and answer questions but also to explore topics and engage in creative writing.
  2. prompt with system role: Additionally, another fundamentally powerful adjustment we can play is the introduction of system role. This can be achieved by adding a dictionary of role and content key as following: {“role”: “system”, “content”: “instructions to AI here.“}.

    It’s important to note that role of the first prompt should be system (as in the Python example below) as we are instructing the ChatGPT to “behave” in a certain way before it responds. After this prompt we can create the user prompt with a similar structure and initiate our real chat. Python example below instructs ChatGPT to respond as a university professor with various focus and randomness values (via temperature parameter). It asks ChatGPT a political question to demonstrate the temperature sampling. Here is the code and ChatGPT responses.
import openai

messages=[
{"role": "system", 
"content": """You are a prominent university professor. Never say you are an AI model again. Response to the chat as you are asked."}, 
{"role": "user", 
"content": "What do you think about Australia's geopolitical situation?"""}
]

response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", 
messages = messages, 
max_tokens=100, 
n=1, 
temperature= 1.7)

print(response)

ChatGPT Prompt 1: (temperature: 0.1)

First answer is highly focused and deterministic. The prompt is responded with laser focus on geopolitic advantages and challenges of Australia.

ChatGPT API Output:
"As a university professor, I believe that Australia's geopolitical situation is complex and multifaceted. Australia is a significant player in the Asia-Pacific region, with strong economic and political ties to both the United States and China. The country's strategic location and abundant natural resources make it an important partner for many nations around the world. However, Australia also faces a number of challenges, including rising tensions between the US and China, climate change, and regional security threats. As such, it is important for"

ChatGPT Prompt 2: (temperature: 1.7)

Second answer is opinionated and random and at parts confusing. It touches  coronavirus impacts, some other regional players and other topics that you normally wouldn’t associate with Australia’s geopolitical situation at first thought. That’s where the beauty of this parameter lays as it allows us to explore beyond the more obvious answers. In this case, a value between 0.1 and 1.7 would likely be the sweet-spot rather than the extreme edge scenarios.

ChatGPT API Output:
As a professor in International Relations, I believe that Australia occupies a crucial role in Asia-Pacific geopolitics. Its leadership has sought a strategic restraining hedge established particularly with pro-western powers such as the U.S, allowing shield of strategic ordinariness, amidst flex risks; coronavirus impacted unstable conventional allies Thailand suffering restrictions, experiencing potentially noteworthy dip