- Python Lesson: APIs with Python
- Python Exercise: APIs with Python
- Mars Weather API
- Dog Pics API
- Sunrise and Sunset API
- Name Generator API
- Space Launch Data API
- Earthquake Data API
- Mars Rover Images API
- Plant Info API
- Special Numbers API
- UK Police Data API
- Nasa Space Image API
- Cocktail Database API
- Official Jokes API
- Chuck Norris Jokes API
- Electric Vehicle Charge Map
- Listing Available OpenAI Models
- ChatGPT API Tutorial
- GPT-4 API Tutorial
- OpenAI Whisper API Tutorial
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.
Content Table
Contents
- What is chatgpt api?
- How to use chatgpt api
- ChatGPT Founders & History
- Learn chatgpt api with python
- Chatgpt api pricing
- gpt1 vs gpt2 vs gpt3 vs gpt3.5 vs gpt-4
- Using Playground AI to test Chatgpt AI model’s parameters
- Getting a full list of all OpenAI models with Python
- Best AI Writing Tool I’ve Ever Used
- ChatGPT API Errors
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.
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
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.
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.
The aggregate forecast time to a 50% chance of HLMI (High Level Machine Intelligence) was 37 years, (*Year 2059)
4- Learn ChatGPT API with Python
openai Python Library
openai library can easily be installed via using pip install command.OpenAI Account for API key
OpenAI API Authorization
openai.api_key combined with the API key you’ve acquired from OpenAI’s developer platform. 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.
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
modelnote: 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.
- Author’s
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
messagesnote: 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.
- Author’s
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_tokensnote: 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.
- Author’s
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
nnote: 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.
- Author’s
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
usernote: 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.
- Author’s
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_biasnote: 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.
- Author’s
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
temperaturenote: 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.
- Author’s
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_pnote: 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.
- Author’s
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
stopnote: It is useful if you don’t want to continue after specific tokens which can be punctuation, words or word groups.
- Author’s
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_penaltynote: 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.
- Author’s
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_penaltynote: 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.
- Author’s
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.
- temperature: Let’s play with the
temperatureparameter. 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. - 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:
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.
