题意:使用 OpenAI API 并尝试通过 os.getenv()
方法来获取 API 密钥,但发现它不起作用
问题背景:
I am just trying some simple functions in Python with OpenAI APIs but running into an error:
在Python中使用OpenAI的API进行一些简单的功能,但遇到了错误
I have a valid API secret key which I am using.
有一个有效的 API 密钥正在使用
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)
问题解决:
Option 1: OpenAI API key not as an environment variable
选项 1:不将 OpenAI API 密钥作为环境变量
Change this... 修改下面的语句
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')
...to this. 修改成
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'
Option 2: OpenAI API key as an environment variable (recommended)
选项 2:将 OpenAI API 密钥作为环境变量(推荐)
Change this... 将下面的语句
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx'
)
...to this... 修改成
openai.api_key = os.getenv('OPENAI_API_KEY')
How do I set the OpenAI API key as an environment variable?
如何将 OpenAI API 密钥设置为环境变量?
STEP 1: Open System properties and select Advanced system settings
步骤 1:打开系统属性并选择高级系统设置
STEP 2: Select Environment Variables
步骤 2:选择环境变量
STEP 3: Select New
步骤 3:选择“新建”
STEP 4: Add your name/key value pair
步骤 4:添加你的名称/键值对
Variable name: OPENAI_API_KEY
Variable value: sk-xxxxxxxxxxxxxxxxxxxx
STEP 5: Restart your computer (IMPORTANT!)
步骤5 重启机器(非常重要!)