A Simple Guide To OpenAI API With Python
A Simple Guide To OpenAI API With Python
Python
ChatGPT API is coming soon, but you can learn how to use
OpenAI API today!
While we don’t know how long that will take, we can familiarize
ourselves with the OpenAI API today!
By learning the OpenAI API today, you’ll be able to access OpenAI’s
powerful models such as GPT-3 for natural language tasks, Codex to
translate natural language to code, and DALL-E to create and edit
original images.
In this guide, we’ll learn how to use OpenAI API with Python.
Before we start working with the OpenAI API, we need to login into
our OpenAI account and generate our API keys.
Image by author
Remember that OpenAI won’t display your secret API key again
after you generate it, so copy your API key and save it.
There are many things we can do with this API. In this guide, we’ll
do text completion, code completion, and image generation.
1. Text Completion
prompt = """
Decide whether a Tweet's sentiment is positive, neutral, or negative.
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
max_tokens=100,
temperature=0
)
print(response)
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"text": "Negative"
}
],
...
}
model :ID of the model to use (here you can see all the models
available)
You can also insert and edit text using the completion and edit
endpoint respectively.
2. Code Completion
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.Completion.create(
model="code-davinci-002",
prompt="\"\"\"\nCreate an array of weather temperatures for Los Angeles\
n\"\"\"",
temperature=0,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
print(response)
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"text": "\n\nimport numpy as np\n\ndef create_temperatures(n):\n
\"\"\"\n Create an array of weather temperatures for Los Angeles\n
\"\"\"\n temperatures = np.random.uniform(low=14.0, high=20.0, size=n)\
n return temperatures"
}
],
...
}
}
If you give proper format to the text generated, you’ll get this.
import numpy as np
def create_temperatures(n):
temperatures = np.random.uniform(low=14.0, high=20.0, size=n)
return temperatures
You can do a lot more, but first I recommend you test Codex in
the Playground (here are some examples to get you started)
3. Image Generation
Here’s the prompt we’ll use (remember that the more detail we give
in the prompt, the more likely we are to get the result we want).
import openai
response = openai.Image.create(
prompt="A fluffy white cat with blue eyes sitting in a basket of
flowers, looking up adorably at the camera",
n=1,
size="1024x1024"
)
image_url = response['data'][0]['url']
print(image_url)
But that’s not all! You can also edit an image and generate a
variation of a given image using the image edits and image
variations endpoints.
That’s it for now! In case you want to check more things you can do
with the OpenAI API, check its documentation.