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

GoogleGenerativeAI API密钥无效错误求助及代码排查

解决GoogleGenerativeAI 400错误:API key无效问题

错误信息

Error: [GoogleGenerativeAI Error]: Error fetching from https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent:
 [400 ] API key not valid. Please pass a valid API key. 

你的代码

import { GoogleGenerativeAI } from "@google/generative-ai";   

const apiKey = process.env.GEMINI_API_KEY as string;  
const genAI = new GoogleGenerativeAI(apiKey);  

const model = genAI.getGenerativeModel({   
  model: "gemini-1.5-flash", 
});  

const generationConfig = {   
  temperature: 1,   
  topP: 0.95,   
  topK: 64,   
  maxOutputTokens: 8192,   
  responseMimeType: "text/plain", 
};  

export const chatSession = model.startChat({   
  generationConfig: generationConfig,   
  history: [], 
}); 

排查与解决步骤

  • 确认环境变量配置
    检查项目根目录的.env文件,确保存在GEMINI_API_KEY=你的密钥这一行,键名拼写完全正确(大小写敏感,不能有多余空格)。如果没有.env文件,手动创建并添加该配置。

  • 验证环境变量是否加载
    在代码中添加日志输出,确认环境变量是否被正确读取:

    console.log("GEMINI_API_KEY:", process.env.GEMINI_API_KEY);
    

    运行项目后,如果输出为undefined,说明环境变量未加载。若使用Node.js,需确保已安装dotenv包,并在项目入口文件顶部添加:

    import dotenv from 'dotenv';
    dotenv.config();
    
  • 检查API密钥有效性
    登录Google AI Studio或Google Cloud控制台,确认你的API密钥:

    • 是为正确的Google Cloud项目生成的
    • 未被禁用或删除
    • 已启用Generative Language API(在Cloud控制台的API库中搜索并启用)
  • 修复代码中的潜在问题
    原代码中的as string断言会掩盖undefined的情况,导致传递无效密钥。修改为以下代码,提前捕获未配置的情况:

    const apiKey = process.env.GEMINI_API_KEY;
    if (!apiKey) {
      throw new Error("环境变量GEMINI_API_KEY未设置,请检查配置");
    }
    const genAI = new GoogleGenerativeAI(apiKey);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:42:15