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

Python中使用有效Google Gemini API Key触发KeyError求助

问题:调用Google Gemini API时触发KeyError

我正在开发一个Python程序,从NASA每日天文图片(APOD)API获取数据,将返回的JSON格式数据转为文本字符串后,因内容过长调用Google Gemini API生成摘要。但使用在Google AI Studio中验证有效的API Key时,程序触发了来自os.py的KeyError。

代码

# imports for functionality
import requests 
import google.generativeai as genai # ai compiler
import os
# requests module -->  allows us to send/recieve packets to/from APIs
# We use 3 APIs in this program; 2 NASA OpenAPIs, and a Google AI api SDK .
# We extract information from the first 2 apis, and summarize using the Google API,
# which is then presented to the user in a simple webpage.

# NASA API config
key = "personal dev key" # --> NASA API key

# Google API config --> migrate to openai after developing ai key
genai.configure(api_key=os.environ["API KEY"]) # --> Google ai API
model = genai.GenerativeModel("gemini-1.5-flash") # --> generates stable model


# API ref dict
apis = {
    "apod" : "https://api.nasa.gov/planetary/apod?api_key="+ key 
}

# check for API error codes
rcodes = {
    200 : "Success",
    301 : "Redirecting",
    400 : "Invalid request",
    401 : "Invalid login",
    403 : "Unauthorized page",
    404 : "Page not found",
    503 : "Server not ready"
}

# Function blocks for parsing each API data
def apod(data):
    # This block appends apod data to data.txt
    f.write(i + ": \n")
    print(data['date']) # date
    f.write(str(data['url'] + "\n")) # url 
    
    imgexp = str(data['explanation']) # vaiable to store explanation
    f.write(imgexp) # <-- writes explanation to data.txt
 
    airesp = model.generate_content("Summarize the following text, prioritizing scientfic information, while keeping it simple enough for someone not the field to understand: " + imgexp)
    print(airesp)
    

f = open("data.txt", "w") # Opens data file in write-over mode

for i in apis: # Runs through api list
    
    # GRABS DATA FROM API: I    
    response = requests.get(apis[i]) # returns status code
    respt = response.json() # Stores text values of api data as a dict
    
    # Delete this part after fully integrated -->
    print(i + "-" + rcodes[response.status_code]) # prints status code 
    print(respt['url']) 
    # Delete this part after fully integrated <--

    # block to determine parsing func
    if i == "apod":
        apod(respt) # <-- passes dict of api response thru parsing function
    else: pass
    

# Call this line last, to enable full data writing
f.close() # Closes file to prevent accidental writing

运行报错

genai.configure(api_key=os.environ['API KEY']) # --> Google ai API
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'API KEY'

解决方案

问题根源

os.environ["API KEY"]尝试读取名为API KEY的环境变量,但系统中并未设置该变量,且带空格的环境变量名不符合常规命名规范。

修复方式

  1. 测试用临时方案:直接将API Key写入代码(仅用于本地测试,生产环境禁止使用):

    genai.configure(api_key="你的Google Gemini API Key")
    
  2. 规范环境变量方案:

    • 设置环境变量:
      • macOS/Linux终端:运行export GOOGLE_API_KEY="你的API Key",然后执行程序;若需持久化,将该行添加到~/.bashrc或~/.zshrc文件中。
      • Windows命令提示符:运行set GOOGLE_API_KEY=你的API Key;PowerShell则运行$env:GOOGLE_API_KEY="你的API Key"。
    • 修改代码:将读取环境变量的代码改为规范的变量名:
      genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
      

内容的提问来源于stack exchange,提问作者Ishaan Rao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:37:29