Colab运行OpenAI订单机器人代码遇API密钥认证及语法错误求助
解决Colab中OpenAI AuthenticationError及语法错误问题
一、直接赋值API密钥的语法错误修复
你写的openai.api_key = <API-KEY>会触发语法错误,因为<API-KEY>是占位符,Python字符串必须用引号包裹。正确写法:
openai.api_key = "sk-你的实际API密钥"
注意:不要在公开代码中直接明文写密钥,避免泄露。
二、Colab中.env文件读取失败的解决方法
Colab是云端环境,本地.env文件无法直接被读取,需按以下步骤处理:
- 上传.env文件到Colab会话:
- 在Colab左侧面板点击「文件」→「上传到会话存储」,选择本地的.env文件。
- 确保.env文件内的变量名是
OPENAI_API_KEY(OpenAI官方默认的环境变量名),内容格式为:OPENAI_API_KEY=sk-你的实际API密钥 - 修改代码中的环境变量读取语句,从
os.getenv('API-KEY')改为:openai.api_key = os.getenv('OPENAI_API_KEY')
- 更安全的替代方案:使用Colab秘密管理:
- 在Colab左侧面板点击「密钥」→「添加密钥」,名称填
OPENAI_API_KEY,值填你的API密钥。 - 代码中替换密钥读取部分:
from google.colab import userdata openai.api_key = userdata.get('OPENAI_API_KEY')
- 在Colab左侧面板点击「密钥」→「添加密钥」,名称填
三、代码中遗漏的函数定义修复
你的collect_messages函数调用了get_completion_from_messages,但代码中未定义该函数,需补充:
def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0): response = openai.ChatCompletion.create( model=model, messages=messages, temperature=temperature ) return response.choices[0].message["content"]
报错信息回顾
AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = ', or you can set the environment variable OPENAI_API_KEY=). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = '. You can generate API keys in the OpenAI web interface.
内容的提问来源于stack exchange,提问作者Antara Raman Sahay
相关产品推荐
相关产品推荐

