I am just trying some simple functions in Python with OpenAI APIs but running into an error:
I have a valid API secret key which I am using.
Code:
>>> import os
>>> import openai
>>> openai.api_key = os.getenv("I have placed the key here")
>>> response = openai.Completion.create(model="text-davinci-003", prompt="Say this is a test", temperature=0, max_tokens=7)
Change this...
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')
...to this.
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'
There are two ways to set the OpenAI API key as an environment variable:
.env
file (easier, but don't forget to create a .gitignore
file) or.env
fileChange this...
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx'
)
...to this...
openai.api_key = os.getenv('OPENAI_API_KEY')
Also, don't forget to use the python-dotenv
package. Your final Python file should look as follows:
# main.py
import os
from dotenv import load_dotenv
from openai import OpenAI
# Load environment variables from the .env file
load_dotenv()
# Initialize OpenAI client with the API key from environment variables
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
)
It's crucial that you create a .gitignore
file not to push the .env
file to your GitHub/GitLab and leak your OpenAI API key!
# .gitignore
.env
STEP 1: Open System properties and select Advanced system settings
STEP 2: Select Environment Variables
STEP 3: Select New
STEP 4: Add your name/key value pair
Variable name: OPENAI_API_KEY
Variable value: sk-xxxxxxxxxxxxxxxxxxxx
STEP 5: Restart your computer (IMPORTANT!)
Your final Python file should look as follows:
# main.py
import os
from dotenv import load_dotenv
from openai import OpenAI
# Initialize OpenAI client
# It will automatically use your OpenAI API key set via Windows Environment Variables
client = OpenAI()