This Paython and OpenAI blog post will show how to save an OpenAI key as an environment variable and authenticate to the platform.
To access the OpenAI API platform and use services like Chat, Images, Audio, files, and more we first need to sign up for a plan and provide a payment method. Each API call is charged per the price of each language model.
The OpenAI pricing model is based on units of 1000 tokens. 1000 tokens are around 750 words and cost $0.003 per 1K input and $0.06 for 1K output. Usage reports are available on the platform management portal.
Once you signup for a plan, you can access the platform. From the platform management portal, click on API Keys and Create a new secret key.
Once you have the secret key, note it and open your IDE.
Create Environment Variable
To create an environment variable, first download the following package
After finishing the installation, create a .env file using the following cmdlet.
You can see in the screenshot below what the .env file looks like.
In the .env file, add the following variable with the API key you noted from the above section.
At this stage, we only need to configure our Python code to access the key and make API calls to the OpenAI platform.
import os import openai from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY")