Gemini said
When you instantiate genai.Client() without passing any arguments, the
Google GenAI SDK automatically looks for your API key in your system's environment
variables.
Specifically, it checks for these two variables:
-
GEMINI_API_KEY(Recommended) -
GOOGLE_API_KEY(Supported as a fallback or for legacy compatibility)
If it finds either of these variables, it automatically injects
the key into the client. If both happen to be set, GOOGLE_API_KEY takes precedence.
Why do it this way?
This is a standard security best practice. By relying on
environment variables rather than explicitly passing the key like genai.Client(api_key="YOUR_KEY"), you avoid
hardcoding sensitive credentials directly into your source code, preventing
accidental leaks if you push your code to a public repository like GitHub.
How to set the environment variable
To make this code work on your machine, you need to set the variable before running your script.
On Mac/Linux (Terminal):
export GEMINI_API_KEY="your_api_key_here"
python your_script.py
On Windows (Command Prompt):
set GEMINI_API_KEY=your_api_key_here
python your_script.py
Alternatively, in Python (using python-dotenv):
If you are using a .env
file to manage your secrets, you can load it before calling the client:
import os
from dotenv import load_dotenv
from google import genai
# This loads the GEMINI_API_KEY from your .env file into the environment
load_dotenv()
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Explain how AI works in a few words"
)
print(response.text)
See All on GenAI « Previously
No comments:
Post a Comment