javascriptvite.envgoogle-geminigoogle-cloud-api-keys

My Gemini API key is not working properly


I am trying to use Google Gemini API to, for that.. I wrote the following code in main.js -

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

// Initialize the model
const genAI = new GoogleGenerativeAI(`${import.meta.env.GEM_API_KEY}`);

const model = genAI.getGenerativeModel({ model: "gemini-pro" });

async function getResponse() {
    const message = await model.generateContent("hi");
    const response = await message.response;
    const text = response.text();

    console.log(text);
}

getResponse();

I have ".env" file containing the api key in the root directory. Its is exactly like..

GEM_API_KEY=my_api_key

It isn't working.. It is showing the the following error -

main.js:9 
        
        
       POST https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent 400 (Bad Request)
makeRequest @ @google_generative-ai.js?v=557eda8f:94
generateContent @ @google_generative-ai.js?v=557eda8f:340
generateContent @ @google_generative-ai.js?v=557eda8f:513
getResponse @ main.js:9
(anonymous) @ main.js:16
Show 3 more frames
Show less
main.js:14 Uncaught (in promise) Error: [400 ] API key not valid. Please pass a valid API key. [{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"API_KEY_INVALID","domain":"googleapis.com","metadata":{"service":"generativelanguage.googleapis.com"}}]
    at makeRequest (@google_generative-ai.js?v=557eda8f:113:13)
    at async generateContent (@google_generative-ai.js?v=557eda8f:340:20)
    at async getResponse (main.js:9:21)

You can also see the screen-shot of the error message on the html rendered page's console..

the error on the html rendered page's console..

I want the response of "hi" from the gemini.. It will be something like, "Hi there, how may I help you?", in the console of the rendered page.. I have cross-checked the api_key, I even created one from my another google account, and.. I have neither shared my api_key to anybody.. nor hosted it on any online platform..

So, I don't know the reason and how to help it. Not getting any help on the browser or gpt.. Would really appreciate the help.


Solution

  • In general, that error message suggests that the API Key isn't actually available in your code. A good first step at debugging it would be to try and get the value inside your code and printing out what it looks like there.

    In this specific case, it sounds like you're using Vite.

    By default for security reasons, Vite only imports variables that start with "VITE_" from the .env files. So starting it with "GEM_" kept it hidden, while it worked when you changed it to "VITE_".

    See https://vitejs.dev/guide/env-and-mode#env-files for details and how you can work around this.