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

Gemini API调用异常:cURL测试成功但Python代码触发KeyError

解决Gemini API调用的KeyError问题

错误原因

你代码里的os.environ[my_API_key]逻辑错误:os.environ是用来读取环境变量名称对应的取值,而你把API密钥字符串直接当作环境变量名去查找,系统中不存在这个名称的环境变量,所以抛出KeyError。

两种可行解决方案

方案1:直接传递API密钥(快速测试用)

修改代码中genai.configure的调用,直接使用你定义的my_API_key变量即可:

import pathlib
import textwrap
import google.generativeai as genai
import os

my_API_key = 'REDACTED'
genai.configure(api_key=my_API_key)  # 直接传入密钥变量

model = genai.GenerativeModel(name='gemini-pro')
response = model.generate_content('Prove the Pythagorean theorem')

print(response.text)

方案2:使用环境变量(更安全,推荐)

把API密钥存入系统环境变量,再通过变量名读取,避免代码中硬编码密钥:

  1. 设置环境变量:
    • Windows(命令提示符):
      set GOOGLE_API_KEY=你的实际API密钥
      
    • Windows(PowerShell):
      $env:GOOGLE_API_KEY="你的实际API密钥"
      
    • Linux/macOS(终端):
      export GOOGLE_API_KEY=你的实际API密钥
      
  2. 修改代码读取环境变量:
    import pathlib
    import textwrap
    import google.generativeai as genai
    import os
    
    genai.configure(api_key=os.environ['GOOGLE_API_KEY'])  # 读取环境变量名对应的值
    
    model = genai.GenerativeModel(name='gemini-pro')
    response = model.generate_content('Prove the Pythagorean theorem')
    
    print(response.text)
    

补充说明

你用cURL测试成功,是因为cURL命令是直接把API密钥作为参数传递,和方案1的逻辑一致;而你之前的代码错误地尝试通过os.environ查找密钥字符串本身,导致了错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:39:58