You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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会话:
    1. 在Colab左侧面板点击「文件」→「上传到会话存储」,选择本地的.env文件。
    2. 确保.env文件内的变量名是OPENAI_API_KEY(OpenAI官方默认的环境变量名),内容格式为:
      OPENAI_API_KEY=sk-你的实际API密钥
      
    3. 修改代码中的环境变量读取语句,从os.getenv('API-KEY')改为:
      openai.api_key = os.getenv('OPENAI_API_KEY')
      
  • 更安全的替代方案:使用Colab秘密管理:
    1. 在Colab左侧面板点击「密钥」→「添加密钥」,名称填OPENAI_API_KEY,值填你的API密钥。
    2. 代码中替换密钥读取部分:
      from google.colab import userdata
      openai.api_key = userdata.get('OPENAI_API_KEY')
      
    这种方式不会在代码中暴露密钥,安全性更高。

三、代码中遗漏的函数定义修复

你的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:12:24