Prerequisites
Before we start, you need to sign up for an API key at the OpenAI API website (https://beta.openai.com/signup/). Once you have an API key, you can use it to access the GPT API.
Installing the Required Libraries
To use the GPT API with Python, we need to install the requests
library. You can install it using pip
:
pip install requests
Making a Request to the GPT API
To generate text using the GPT API, we need to send a POST
request to the API endpoint with the following parameters:
model
: The name of the GPT model to use.prompt
: The text prompt to feed to the model. This can be a single sentence or a paragraph.max_tokens
: The maximum number of tokens (i.e., words and punctuations) to generate.temperature
: The temperature to use when sampling from the model. A higher temperature will result in more diverse and creative output, while a lower temperature will result in more predictable and conservative output.
Here’s an example of how to make a request to the GPT API using the requests
library:
import requests
def chatGPT(text):
url = "https://api.openai.com/v1/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR-API-KEY",
}
data = {
"model": "text-davinci-003",
"prompt": text,
"max_tokens": 4000,
"temperature": 1.0,
}
response = requests.post(url, headers=headers, json=data)
output = response.json()[‘choices’][0][‘text’]
return print(output)
Example:
That’s all!
How to get your API?
- Go to the OpenAI website (https://beta.openai.com/).
- Login or Signup if you didn’t have the account.
- Click on your profile at the top right
- Click on the “View API keys”.
- Click on the “Create new secret key”
- The API key will be displayed on the screen.