Google Gemini API Setup Guide

Step-by-Step Setup

1. Create and Activate Virtual Environment

# Create a new virtual environment
python -m venv genvp
source genvp/bin/activate

2. Install the Library

pip install google-genai

3. Get Your API Key

  1. Go to Google AI Studio
  2. Click "Create API Key"
  3. Copy your API key

4. Set Your API Key as Environment Variable

#!/bin/bash
set -a
export GOOGLE_API_KEY="your_actual_api_key_here"

5. Create Your Hello World Script

Create a file called hello.py:

from google import genai
import os

# Create client with API key from environment
client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))

# Generate content using the full model path
response = client.models.generate_content(
    model="models/gemini-2.5-flash",
    contents="Say hello and introduce yourself in one sentence"
)

print(response.text)

6. Run It

python hello.py

Key Points

  • Import: Use from google import genai (NOT google.generativeai)
  • Model names: Must include the models/ prefix (e.g., "models/gemini-2.5-flash")
  • Client-based: Uses genai.Client() to create a client instance

Listing Available Models

To see what models are available to your account:

from google import genai
import os

client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))

print("Available models:")
for model in client.models.list():
    print(f"  - {model.name}")

Common Models

  • models/gemini-2.5-flash - Fast, efficient model
  • models/gemini-2.5-pro - More capable model
  • models/gemini-3-flash-preview - Latest experimental flash model
  • models/gemini-3-pro-preview - Latest experimental pro model

Troubleshooting

"No module named 'google.genai'"

  • Ensure your virtual environment is activated
  • Run pip list to verify installation

"RESOURCE_EXHAUSTED" or quota errors

"NOT_FOUND" model errors

  • Use client.models.list() to see available models
  • Make sure to include the models/ prefix in model names
Description
No description provided
Readme 26 KiB
Languages
Python 100%