How to call GPT-3 API in Python


In this article, I will show you how to access GPT3 API in python and how to use it for text generation.

Get your OpenAI key

To get your OpenAI key, go to and create an account by entering in your email address and password.

Once you have registered for an account, you will receive a confirmation email from OpenAI containing information about what to do next—this is when it’s time for the next step!

Install the openai python library

This article assumes that you are familiar with Python and have a working installation of Python. If you’re not sure if you have a working Python environment, check out this website.

Once you have confirmed that you have a working python installation, follow below steps to install openai python library:

  1. Open your command line or terminal app and run the below command:

  2. simply run the following command:

    !pip install openai

using openai python library to call gpt-3 api

Now we will make use of the openai library for GPT-3 which contains various tools for interacting with GPT-3 including loading models, parsing data and generating possible responses from a given model.

To begin using this library, type below in a python console or in a python file:

Here is the python code to call the GPT-3 API:

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
prompt="Write an extremely long, detailed answer to \"How to Cut Corners Using CSS Mask and Clip Path Properties\". Use HTML formatting.",


Code Explnation

The code above is a Python 3 script that
- uses the OpenAI API to generate a response to the prompt “Write an extremely long, detailed answer to "How to Cut Corners Using CSS Mask and Clip Path Properties". Use HTML formatting.”.
- The response is generated using the text-davinci-002 engine, which is a GPT-3 AI model.
- The response is generated with a temperature of 0.7, a maximum of 709 tokens, a top_p of 1, a frequency_penalty of 0, and a presence_penalty of 0.
- And finally the response is then printed to the console.


Now you’re ready to call the GPT-3 API and marvel at what it can do! Taking these steps will only make the process easier, allowing you to generate text with the push of a button.

Some of my other GPT-3 posts: