Environment variables and dotenv
Every AI project starts the same way: load_dotenv(), then os.getenv() for your API keys and model names. This pattern keeps secrets out of your code and makes switching models a one-line config change.
Secure config loading
How .env files keep API keys out of your code
import os
# os.getenv() reads environment variables
home = os.getenv("HOME")
print(f"Home directory: {home}")
# With a default (the pattern used in ALL AI courses)
model = os.getenv("DEFAULT_MODEL", "gemini/gemini-2.0-flash")
print(f"Model: {model}")
db_path = os.getenv("DB_PATH", "ecommerce.db")
print(f"Database: {db_path}")os.getenv(key, default) reads an environment variable. If not set, it returns the default. This is how AI projects handle configuration without hardcoding values.
If you hardcode an API key and push to GitHub, anyone can steal it and run up charges on your account. The .env file stays local (add it to .gitignore), and load_dotenv() loads it at runtime. This is a security best practice for all software, not just AI.
import os
from dotenv import load_dotenv
# Load .env file into environment
load_dotenv()
# Now these are available via os.getenv
model = os.getenv("DEFAULT_MODEL", "gemini/gemini-2.0-flash")
embedding = os.getenv("EMBEDDING_MODEL", "google/text-embedding-004")
print(f"Model: {model}")
print(f"Embedding: {embedding}")load_dotenv() reads your .env file and sets those values as environment variables. Then os.getenv() can access them.
Here is what the .env file itself looks like. It is just key=value pairs, one per line. Remember to add .env to your .gitignore so you never accidentally push secrets to GitHub.
# Your .env file (add to .gitignore!)
DEFAULT_MODEL=gemini/gemini-2.0-flash
EMBEDDING_MODEL=google/text-embedding-004
GOOGLE_API_KEY=your_key_here
APP_NAME=Green Bites AIThe .env file stores secrets and config. Never commit this file. Copy .env.example to .env and fill in your values.
Quiz: Quiz
Loading practice…
Ordering exercise: AI project setup order
Loading practice…
Validation checklist: Environment setup checklist
Loading practice…
Checkpoint: Genai toolkit checkpoint
Loading practice…
Timed quiz: Genai toolkit speed round
Loading practice…