Using FREE Gemini API with Fallback

Agentic AI
NLP
Author

Suraj Jaiswal

Published

September 10, 2025

This guide explains how to set up the Google AI Studio API key, install dependencies, and call Gemini models with Python.

🔑 Get your API key from Google AI Studio — no credit card required.

⚡ The free tier comes with daily rate limits, so here we’ll simply configure fallback models to maximize your total number of Request per day of API calls.

1. Gemini Model Rate Limits

Here’s a quick reference table of available Gemini models and their limits:

Model RPM TPM RPD
Gemini 2.5 Pro 5 250,000 100
Gemini 2.5 Flash 10 250,000 250
Gemini 2.5 Flash-Lite 15 250,000 1,000
Gemini 2.0 Flash 15 1,000,000 200
Gemini 2.0 Flash-Lite 30 1,000,000 200

2. Install Dependencies:

Make sure you have the latest google-genai package:

!pip install -q -U google-genai

⚡ Use Flash or Flash-Lite models for higher throughput or lightweight tasks. Use Pro for better reasoning and accuracy.

3. Set Up the API Key

Save it in an environment variable GEMINI_API_KEY.

import os

# Set the environment variable
os.environ["GEMINI_API_KEY"] = "your_api_key_here"

# Verify
print(os.environ["GEMINI_API_KEY"])

4. First API Call

Here’s a simple example using Gemini 2.5 Pro:

from google import genai

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents="Explain India in few crisp points"
)
print(response.text)
Of course. Here is India explained in a few crisp points:

*   **A Land of Immense Diversity:** Home to over 1.4 billion people, India is a mosaic of countless cultures, languages (22 official), and religions (birthplace of Hinduism, Buddhism, Jainism, and Sikhism). The phrase "Unity in Diversity" is its essence.

*   **The World's Largest Democracy:** It is a federal parliamentary republic with a robust electoral system. Despite its complexities, democratic traditions are deeply rooted.

*   **A Fast-Growing Major Economy:** India has one of the world's fastest-growing economies, driven by a powerful service sector (especially IT), a large industrial base, and a significant agricultural sector.

*   **An Ancient Civilization:** Boasting a history of over 5,000 years, it has been home to ancient civilizations (Indus Valley), powerful empires (Mauryan, Gupta, Mughal), and a colonial past, culminating in a non-violent independence movement led by Mahatma Gandhi.

*   **Rich Cultural Influence:** A global hub for spirituality, yoga, vibrant cuisine, classical arts, and a massive film industry known as "Bollywood."

*   **A Nation of Contrasts:** India is a study in contrasts, where ancient traditions coexist with modern technology, immense wealth with significant poverty, and serene landscapes with bustling, chaotic cities.

5. Fallback Mechanism with Multiple Models

To make your app more resilient, you can try multiple models in order. If one fails (due to quota or availability), the next one is used automatically.

from google import genai

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()

MODELS = [
    "gemini-2.5-pro",
    "gemini-2.5-flash",
    "gemini-2.5-flash-lite",
    "gemini-2.0-flash",
    "gemini-2.0-flash-lite",
]

def generate_text(prompt: str) -> str:
    """
    Try each model in order and return the response text 
    from the first model that works.
    """
    for model in MODELS:
        try:
            response = client.models.generate_content(
                model=model,
                contents=prompt
            )
            print(f"✅ Success with model: {model}")
            return response.text
        except Exception as e:
            print(f"⚠️ Failed with model {model}: {e}")
    return "❌ All models failed."
text = generate_text("Explain India in few crisp points")
print("\nFinal Response:\n", text)
✅ Success with model: gemini-2.5-pro

Final Response:
 Of course. Here is an explanation of India in a few crisp points:

*   **World's Largest Democracy:** With over 1.4 billion people, it is the most populous democracy on Earth, known for its vibrant and complex political landscape.

*   **Ancient Civilization, Modern Nation:** Home to one of the world's oldest civilizations (Indus Valley), it is the birthplace of major religions like Hinduism, Buddhism, and Jainism. Today, it balances ancient traditions with modern aspirations.

*   **A Fast-Growing Economic Power:** It is one of the world's fastest-growing major economies, a global hub for IT and software services, and has a successful space program (ISRO).

*   **Unmatched Diversity:** India is a mosaic of cultures, with over 22 official languages, countless dialects, diverse cuisines, colourful festivals, and a vast array of ethnic groups living together.

*   **Incredible Geographic Variety:** Its landscape spans from the snow-capped Himalayas in the north to tropical beaches in the south, encompassing vast deserts, fertile plains, and dense forests.

References

  1. Google docs: https://ai.google.dev/gemini-api/docs
  2. Rate limits: https://ai.google.dev/gemini-api/docs/rate-limits#free-tier