GoogleGenerativeAIError: [400 Bad Request] API key not valid. Please pass a valid API key

1.9k views Asked by At

I am following this tutorial from Google on using Gemini in Node applications; I have followed all the steps, created an API key from Google AI Studio; encased it inside an env file, and called it in the app.js file to generate text as seen from this snippet of code

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

async function run() {
  // For text-only input, use the gemini-pro model
  const model = genAI.getGenerativeModel({ model: "gemini-pro"});

  const prompt = "Write a story about a magic backpack."

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

Unfortunately when I run node app in the terminal I get this error Error Messageinstead of receiving a response; I have tried google searches and chat GPT and came up with nothing substantial or helpful.

Any pointers to resources that can help me solve this error are greatly appreciated and welcomed. Thanks

2

There are 2 answers

1
ZICHENG SHAN On

Please make sure your node version is >= 18.

1
Samson Royal On

I spoke to a friend and realized that the API key was right but it wasn't being parsed the right way in the app.js file

I had to run npm install dotenv --save to install the dotenv package and after which I added the line as seen in the code below

Line of code added

This solved the error and successfully gives me a response as seen below Response in the terminal