安装OPENAI的包
pip install --upgrade openai
而后从chatgpt官网得到相应的API
注意:key只会出现一次所以要自己记好
而后打开电脑:系统-->系统信息-->高级系统设置-->系统属性中的“高级”-->环境变量-->新建系统变量。
变量名:OPENAI_API_KEY
变量值:保存的密钥
而后打开python进行测试:
中间遇到一个BUG,报错如下:
openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details.
解决方案,代码改为如下形式:
import os
import openai
# 创建一个 GPT-3 请求
openai.api_key = "密钥"
# openai.organization =
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo-16k",
messages=[
{"role": "user", "content": "Hello, Nice to meet you"}
]
)
print(completion.choices[0].message)