首页 > 解决方案 > 如何将 API 密钥存储在环境变量中?并在 google colab 中调用相同的

问题描述

我不确定如何使用我的 GPT-3 API 密钥/环境变量制作“.json”文件,但我想在 Google Colab 中使用它来自动生成代码。

有人可以告诉我怎么做吗?

我想使用下面的代码从 .json 文件中获取 API 密钥。

with open('GPT_SECRET_KEY.json') as f:
    data = json.load(f)
openai.api_key = data["API_KEY"]

标签: pythonenvironment-variablesgpt-3

解决方案


要从 json 文件中读取,请执行以下操作:

import json

my_key = ''
with open('GPT_SECRET_KEY.json', 'r') as file_to_read:
    json_data = json.load(file_to_read)
    my_key = json_data["API_KEY"]

你的 json 文件的结构应该是这样的。

{
    "API_KEY": "xxxxthis_is_the_key_you_are_targetingxxxx", 
    "API_KEY1": "xxxxxxxxxxxxxxxxxxxxxxx",
    "API_KEY2": "xxxxxxxxxxxxxxxxxxxxxxx"
}

如果我的回答不够清楚,这里是一个类似问题的链接。


推荐阅读