In this tutorial, we will learn how to use OpenAI ChatGPT (GPT4) API in Python.

If you have never heard of OpenAI before, OpenAI is the company that developed ChatGPT, and OpenAI API is the service that allows developers to access the AI models that creates ChatGPT through REST API.

Step 1: Create an OpenAI account

The first step to getting started with OpenAI GPT API is to create an account on the OpenAI website. Go to and sign up for an account.

Step 2: Generate OpenAI API key

To connect to OpenAI API endpoint, we need to first create a secret key. Click on your user name, then click on View API keys. Click Create new secret key button to generate an API key.

Step 3: Install the OpenAI API package

The OpenAI API package can be installed using the pip package manager in Python. Open a terminal and type the following command to install the package:

pip install openai    

Step 4: Connect to OpenAI In Python

To connect to OpenAI endpoint, we will import the openai modle and attach the API key

import openai

API_KEY = '<openAI API key>'
openai.api_key = API_KEY

Source Code:

import openai

API_KEY = '<api key>'
openai.api_key = API_KEY
model_id = 'gpt-4'

def chatgpt_conversation(conversation_log):
    response = openai.ChatCompletion.create(

        'role': response.choices[0].message.role, 
        'content': response.choices[0].message.content.strip()
    return conversation_log

conversations = []
# system, user, assistant
conversations.append({'role': 'system', 'content': 'How may I help you?'})
conversations = chatgpt_conversation(conversations)
print('{0}: {1}\n'.format(conversations[-1]['role'].strip(), conversations[-1]['content'].strip()))

while True:
    prompt = input('User: ')
    conversations.append({'role': 'user', 'content': prompt})
    conversations = chatgpt_conversation(conversations)
    print('{0}: {1}\n'.format(conversations[-1]['role'].strip(), conversations[-1]['content'].strip()))