How to Use ChatGPT API in Python?


Introduction

Generative AI has been on the popular rounds for quite some time now and almost everyone is aware of ChatGPT, the popular Generative AI developed by OpenAI. Apart from using the platform as a chatbot, we can also use the ChatGPT API to implement code and build amazing applications for various use cases.

In this article, we will be going through how we can use the OpenAI API in Python programming language to build something out of it and look at a few use cases as well.

What is ChatGPT API?

ChatGPT is a large language model developed by OpenAI. It is based on GPT-3 and GPT-4 (free and premium versions respectively). ChatGPT is trained on a huge dataset and is quite advanced than the average Generative AIs out there.

ChatGPT can take natural language prompts as inputs from human-generated content and return professional-looking and almost accurate information or task completion. People and businesses all over the world use this to perform a lot of tasks, especially the ones that usually require human intervention.

So, the ChatGPT API is a service of its own offered by OpenAI to let developers and businesses use the power of OpenAI GPT-3 and/or GPT-4 language. One can use it to build stand-alone applications for personal or business purposes or even just use it to explore or for testing.

ChatGPT API Pricing

ChatGPT API has two pricing models currently - the ChatGPT Plus Subscription and Pay-as-you-go Price. However, you can use the Open AI ChatGPT API for free if you have a fresh account which comes with 18 credits for the first 3 months.

With that, let’s look at the pricing models in detail.

ChatGPT Plus Subscription

OpenAI has introduced a subscription plan called "ChatGPT Plus”. This is priced at $20/month. Subscribers of ChatGPT Plus receive many benefits. The benefits include general access to ChatGPT (even during peak times) faster response times, and priority access to new features and improvements. This subscription plan is available to customers all around the world.

Pay-as-you-go Pricing

OpenAI also offers a pay-as-you-go pricing model for the ChatGPT API. Developers can start exploring first with $5 in free credit during the first three months of usage. After this initial free credit is done, users only pay for the resources they use.

The pay-as-you-go pricing allows for flexibility and cost-effectiveness. This is because users are charged based on the number of API calls and resources consumed. You can find the specific pricing details of the sub-plans under this on OpenAI’s pricing page.

How to use ChatGPT API with Python?

In order to get started with the implementation of the Python code, first we need to set up the API keys and environment in Python. After this, proceed to write the Python code and complete using the API to build our version of ChatGPT in our system itself.

The following are the steps we need to follow to use OpenAI in Python.

Step 1 − The first step is to open an OpenAI account and API key.

  • If you have an OpenAI account already, log in to your account. After that click on your profile icon in the top right corner. You will find “View API keys”. For this, click on “Create a new secret key” and create one here.

    If you don’t have an account, create an account using any signup method of your choice then follow the same.

  • After creating a new secret key, copy this secret key. Then, save this somewhere wherever you want.

Step 2 − Now, we have to Install the OpenAI library in Python.

  • First, we need to check the Python version to make sure that your Python version is or above 3.7.1.

python --version
  • Now, lets create a Python environment on our system.

In Windows −

PS> python -m venv venv
PS> .\venv\Scripts\activate

In Linux/MacOS −

$ python -m venv venv
$ source venv/bin/activate
  • Install the OpenAI library using pip.

python -m pip install openai

Step 3 − Setting up the Environment with API key.

Now that you have the OpenAI Python library installed, you need to set up your environment with the API key. To do this, you can use an environment variable to store your API key. This will make it available to your Python scripts.

In Windows −

(venv) PS> $ENV:OPENAI_API_KEY = "<your-key-value-here>"

In Linux/MacOS −

(venv) $ export OPENAI_API_KEY="<your-key-value-here>"

Replace “<your-key-value-here>” with your API secret key that you had stored earlier.

Step 4 − Now, we will add the Python Code to implement the API.

In the below code has the following features −

  • Importing the openai library to implement it

  • Declaring the API secret key we acquired from our OpenAI account.

  • Infinite loop to chat with GPT without limit or stop unless we want to.

  • Storing User prompt in a variable called “message”.

  • Use the ‘openai.ChatCompletion.create()’ to generate an answer from the ChatGPT API based on the user prompt.

  • Storing this answer in the variable called ‘answer’ and returning using print function.

Filename − chatgpt-app.py

import openai
openai.api_key = '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'
messages = [ {"role": "system", "content":"You are a intelligent assistant."} ]
while True:
   message = input("User : ")
   if message:
      messages.append(
         {"role": "user", "content": message},
      )
      chat = openai.ChatCompletion.create(
         model="gpt-3.5-turbo", messages=messages
      )
   answer = chat.choices[0].message.content
   print(f"ChatGPT: {answer}")
   messages.append({"role": "assistant", "content": answer})

Run the following command in your terminal to kick-start your ChatGPT chatbot in your terminal.

python chatgpt-api.py

Output

Your chatgpt chatbot is ready to take your inputs and respond!

Conclusion

In this article, we learnt about ChatGPT API. Then, we went about finding out how to implement it using Python.

After that, we looked at how to create an account on the OpenAI platform. Then, how to generate the API secret key.

After we finished all this, we went through the entire Python code to implement this. Then, we ran it in our terminal with user inputs.

You can use the ChatGPT API to do a lot of things and build many applications. With generative AI, the sky is the limit!

Updated on: 23-Jan-2024

39 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements