How to get an openAI API key and how to use it in Python

2023年7月27日

I got the API key provided by OpenAI, which is a hot topic in ChatGPT, and tried to check the operation of the openai module from Python. To obtain an API key, register as a member on the OpenAI website. You can try it for free during the free trial period ($5 worth) after registration, but you will be charged for use after that.
You can check the detailed fee structure from the OpenAI website.

Execution environment: macOS Python3.9




 

How to get openAI API key

First, open the following address of openai.com and register to obtain an API key.
Click “Get started“.
https://openai.com/product

On the Create your account page, you can register with either an email address, a Google account, or a Microsoft account. This time, I registered with my email address. Enter your email address and click “Continue".

Enter the registration fee password and click “Continue“.

A confirmation email will be sent from OpenAI to the registered email address.
Open the linked page in the email and click “Verify email address“.

Enter your first and last name on the Tell us about you page.

Registration will be confirmed by SMS authentication.
Register your mobile number and click “Send code“.

Enter the number received by text message on your mobile in Enter code.

After entering the code, the OpenAI member web page will automatically open with you logged in.
Click [Personal]-[View API keys] at the top right of the page.

On the API keys page, click “+ Create new secret key“.

This will generate an API key. Copy with the button to the right of the key.

Don’t forget to save the copied API key. Then use this API key to generate a program.
This completes user registration and API key acquisition.




How to use API key in Python

Install openai module in Python

openai module install from pip command

$ pip install openai

First, set the API key obtained earlier as an environment variable.
Add the following code to your .bash_profile.

export OPENAI_API_KEY="Enter your API key"

reflect the settings.
$source .bash_profile

Below is an example of simple chat, text and image generation using the openai module.

・Example using gpt-3.5-turbo model

import os
import openai

# Get API key from environment variable
openai.api_key = os.environ["OPENAI_API_KEY"]

# Assign the question's answer to the res variable
res = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Tell me about YMO in Japan."},
    ],
)
# output reply
print(res.choices[0]["message"]["content"])

[Output result]

Yellow Magic Orchestra (YMO) is a legendary Japanese electronic music group that formed in Tokyo in 1978. The band consists of three members, Haruomi Hosono, Ryuichi Sakamoto, and Yukihiro Takahashi.

YMO is often credited as pioneers in the development of electronic music, and they were a prominent figure in the Japanese music scene throughout the 1980s. Their unique blend of traditional Japanese music with electronic elements, as well as their use of innovative instruments such as the Roland TR-808 drum machine, made them a groundbreaking force in the industry.

YMO’s influence has reached far beyond Japan, with many contemporary artists citing them as inspiration. They have released numerous albums throughout their career, including “Yellow Magic Orchestra" (1978), “Solid State Survivor" (1979), and “Technodelic" (1981).

In addition to their musical contributions, YMO has been noted for their experimentation with fashion and technology, as well as their incorporation of visual elements into their live performances. They remain a significant cultural icon in Japan and have continued to influence the electronic music genre to this day.

・Example using the text-davinci-003 model

import os
import openai

# Get API key from environment variable
openai.api_key = os.environ["OPENAI_API_KEY"]

# Assign the question's answer to the res variable
res = openai.Completion.create(
    model="text-davinci-003",
    prompt="What is the impact of AI on the economy in the future and the problems it will create?",
    max_tokens=1024,
    temperature=1,
)
# output reply
print(res.choices[0].text)

[Output result]
The potential of AI to reshape the economy is vast. AI is capable of performing different types of tasks more efficiently and more accurately than humans, enabling businesses to realize dramatic cost savings and productivity gains. AI is now being used across multiple industries, including retail, finance, healthcare, logistics, transportation, and more. AI will enhance the way businesses interact with customers, helping them to better understand customer preferences, improve customer service, and increase profits. Furthermore, AI will enable businesses to uncover new markets and opportunities.

However, the implementation of AI may also create new problems that businesses need to be aware of. These problems include increased transparency and data security risks, as AI is heavily reliant on collecting and storing data. AI can also lead to job displacement as businesses further automate their processes. In addition, there is the potential for new forms of discrimination as AI algorithms can become biased towards specific populations without proper precautions in place. Finally, AI raises ethical considerations in terms of privacy and transparency, which businesses need to take into account.

・Example using the DALL-E model

import os
import openai

# Get API key from environment variable
openai.api_key = os.environ["OPENAI_API_KEY"]

# generate image
response = openai.Image.create(
  prompt="Mount Fuji and cherry blossoms",
  n=1,
  size="512x512"
)

# URL of generated image
image_url = response['data'][0]['url']

# View generated image URL
print(image_url)

[Output result]