ANTIGRAVITY LABJP
Articles/Tips & Best Practices
Tips & Best Practices/2026-04-17Intermediate

When the google-genai SDK Refuses to Work — Diagnosing and Fixing Python API Errors in Antigravity

A practical guide to diagnosing and fixing the most common google-genai SDK errors in Antigravity: authentication failures, ImportError, deprecated model names, and rate limiting — with working code examples for each.

python26google-genai5api13troubleshooting105error-fix4antigravity432

Within the first few minutes of using the google-genai SDK with Python, you will almost certainly run into at least one error. Unauthenticated, ImportError, 404 model not found — these messages appear without much explanation of what actually went wrong or where to start looking.

I hit the same wall when I started using google-genai seriously inside Antigravity. This guide collects the error patterns I've encountered most often and walks through each one with a concrete fix. If you have an error message in hand, you can jump straight to the section that matches it.

Authentication Errors: Unauthenticated / API_KEY_INVALID

Authentication errors are the most common starting point. You might see any of the following:

google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials.
google.api_core.exceptions.PermissionDenied: 403 API key not valid. Please pass a valid API key.

There are two root causes worth checking: the API key is not being passed correctly, or the key doesn't have the Generative Language API enabled in Google Cloud Console.

The google-genai SDK (version 1.0+) changed how you initialize a client. If you learned from older tutorials that use google-generativeai, the code looks different enough to cause confusion.

# Old package (google-generativeai) — deprecated
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY")
 
# New package (google-genai) — current
from google import genai
 
client = genai.Client(api_key="YOUR_API_KEY")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Hello from Antigravity\!"
)
print(response.text)

One detail that trips people up: google-generativeai and google-genai are separate packages with similar names, but the import paths are different. Run this in Antigravity's terminal to see which one is actually installed:

pip list | grep google-gen
# google-genai          1.x.x   ← new package
# google-generativeai   0.x.x   ← old, deprecated

If your API key is set up correctly but you still see a 403, go to Google AI Studio and check that the key you're using has the Generative Language API enabled.

ImportError: Package Name Confusion

ImportError: cannot import name 'genai' from 'google'
ModuleNotFoundError: No module named 'google.generativeai'

When this happens, the import statement in your code doesn't match the package that's actually installed in your environment.

# If google-genai is installed:
from google import genai          # ✅ correct
import google.generativeai as genai  # ❌ this is for the old package
 
# If google-generativeai is installed:
import google.generativeai as genai  # ✅ correct for old package
from google import genai          # ❌ wrong for old package

In Antigravity, a common cause is installing a package globally but running code inside a virtual environment where that package isn't present. If your project has a .venv folder, activate it before installing:

# In Antigravity's terminal
python -m venv .venv
source .venv/bin/activate       # Mac/Linux
.venv\Scripts\activate          # Windows
pip install google-genai

After activating the virtual environment, check that Antigravity is using the right Python interpreter. Open the Command Palette (Cmd+Shift+P) and run Python: Select Interpreter, then select the .venv Python. This ensures the packages you install are the ones the editor actually runs.

NotFound: Deprecated Model Names

google.api_core.exceptions.NotFound: 404 models/gemini-pro is not found for API version v1beta

Google retires models on a rolling basis. Tutorials written a year ago often reference model names that no longer work.

# ❌ Model names that are outdated or unavailable
model="gemini-pro"
model="gemini-1.0-pro"
model="models/gemini-pro"
 
# ✅ Recommended model names as of 2026
model="gemini-2.0-flash"          # fast, well-balanced — good default
model="gemini-2.5-pro-preview"    # high capability, higher cost
model="gemini-2.0-flash-lite"     # lightweight, lowest cost

If you want to see the full list of models available to your API key at any given time, you can fetch it programmatically:

from google import genai
 
client = genai.Client(api_key="YOUR_API_KEY")
 
for model in client.models.list():
    if "generateContent" in model.supported_generation_methods:
        print(model.name)
 
# Example output:
# models/gemini-2.0-flash
# models/gemini-2.0-flash-lite
# models/gemini-2.5-pro-preview

The name field comes back as models/gemini-2.0-flash, but you can pass either the full path or just gemini-2.0-flash to generate_content() — both work.

ResourceExhausted: Dealing with Rate Limit Errors

google.api_core.exceptions.ResourceExhausted: 429 Quota exceeded for quota metric 'generate_requests_per_minute_per_project_per_base_model'

On the free tier this is a regular occurrence, especially when you're testing loops or batch requests. Simply retrying immediately will just hit the same limit. The reliable fix is exponential backoff with a small random jitter:

import time
import random
from google import genai
from google.api_core import exceptions
 
def generate_with_retry(client, model, contents, max_retries=5):
    """Retries generate_content with exponential backoff on rate limit errors."""
    for attempt in range(max_retries):
        try:
            response = client.models.generate_content(
                model=model,
                contents=contents
            )
            return response
        except exceptions.ResourceExhausted:
            if attempt == max_retries - 1:
                raise  # Give up after max retries
            
            # Exponential backoff + jitter
            wait = (2 ** attempt) + random.uniform(0, 1)
            print(f"Rate limited. Retrying in {wait:.1f}s (attempt {attempt + 1}/{max_retries})")
            time.sleep(wait)
        except exceptions.GoogleAPIError:
            raise  # Re-raise non-rate-limit errors immediately
 
client = genai.Client(api_key="YOUR_API_KEY")
response = generate_with_retry(client, "gemini-2.0-flash", "Write a quicksort in Python")
print(response.text)

The jitter (random.uniform(0, 1)) is important when you're running multiple processes at once — without it, all instances retry at the same moment and hit the rate limit again simultaneously.

For more complex scenarios, the tenacity library (pip install tenacity) handles retry logic cleanly with decorators.

Virtual Environment and Environment Variable Pitfalls in Antigravity

Hardcoding an API key into your source file is fine for a quick experiment, but you'll want to use environment variables for anything that gets committed to git. Here's a setup that works reliably in Antigravity:

from dotenv import load_dotenv  # pip install python-dotenv
import os
from google import genai
 
load_dotenv()  # Reads from .env in the current working directory
 
api_key = os.environ.get("GOOGLE_API_KEY")
if not api_key:
    raise ValueError(
        "GOOGLE_API_KEY is not set. "
        "Add it to a .env file in your project root."
    )
 
client = genai.Client(api_key=api_key)

Two things to watch for in Antigravity specifically:

Working directory mismatch: When you open a terminal inside Antigravity, the current directory may not be your project root. If load_dotenv() can't find your .env file, run os.getcwd() to see where Python is looking. You can pass an explicit path: load_dotenv(dotenv_path="/absolute/path/to/.env").

Variable name: The google-genai SDK looks for GOOGLE_API_KEY by default. Some older code and tutorials use GEMINI_API_KEY. If you're seeing an authentication error despite having a .env file, check which variable name your code actually reads.

Streaming Responses: TypeError and Incomplete Output

If you're using streaming (stream=True) and running into TypeError or seeing only partial output, the iteration pattern matters:

from google import genai
 
client = genai.Client(api_key="YOUR_API_KEY")
 
# ❌ Wrong — this may not capture all chunks
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Explain async/await in Python",
    stream=True
)
print(response)  # This won't give you useful output
 
# ✅ Correct — iterate over the stream
for chunk in client.models.generate_content_stream(
    model="gemini-2.0-flash",
    contents="Explain async/await in Python"
):
    print(chunk.text, end="", flush=True)
 
print()  # Final newline

Note that the streaming method name is generate_content_stream, not generate_content with stream=True. This changed between SDK versions and is a common source of confusion when following older examples.

If chunks come through but the final output seems cut off, check whether your terminal buffer is flushing correctly — the flush=True argument on print() ensures each chunk appears immediately rather than being held in a buffer.

Using the Async Client in Antigravity

If you're integrating the SDK into an async application (FastAPI, for example), the synchronous client will block the event loop. Switch to the async client instead:

import asyncio
from google import genai
 
async def get_response(prompt: str) -> str:
    client = genai.Client(api_key="YOUR_API_KEY")
    
    response = await client.aio.models.generate_content(
        model="gemini-2.0-flash",
        contents=prompt
    )
    return response.text
 
async def main():
    result = await get_response("What is the Antigravity IDE?")
    print(result)
 
asyncio.run(main())

The async client lives at client.aio — so client.aio.models.generate_content() instead of client.models.generate_content(). This is another API surface that changed between SDK versions, and mixing sync and async calls is a reliable way to produce confusing errors.

If you see RuntimeError: This event loop is already running when calling the sync client from within an async context (common in Jupyter notebooks running inside Antigravity), the fix is either to switch to client.aio or to use asyncio.run() in a separate thread.

Quick Diagnostic Checklist

If an error isn't covered above, work through these checks in order:

Step 1: Confirm what's installed

pip list | grep google-gen
python -c "from google import genai; print(genai.__version__)"

Step 2: Test the API key directly

curl -H "x-goog-api-key: YOUR_API_KEY" \
  "https://generativelanguage.googleapis.com/v1beta/models"

A 200 response means the key works. A 401 or 403 means it doesn't — check the key and its enabled APIs in Google Cloud Console.

Step 3: Verify the model name — use the client.models.list() snippet above.

Step 4: Check the virtual environment

which python
pip show google-genai

One last thing that's saved me time more than once: pasting the full error message and stack trace directly into Antigravity's chat and asking for the cause and fix. A complete stack trace gives the AI much more to work with than a summary.

Start with pip list | grep google-gen — it takes ten seconds and resolves more issues than any other single check.


Share

Thank You for Reading

Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Tips2026-05-12
4 Runtime Error Patterns from Gemma 4-Generated Code in Antigravity — and How to Fix Them
Gemma 4 writes clean-looking code — until it runs. This guide covers the four most common runtime error patterns in Antigravity-generated Python code: TypeError, AttributeError, asyncio issues, and import conflicts.
Tips2026-04-15
How to Fix Package & Module Errors in Antigravity [2026 Guide]
Learn how to diagnose and fix package and module errors in Antigravity-generated code. This practical guide covers Cannot find module errors, version conflicts, path alias issues, and TypeScript declaration problems.
Integrations2026-04-19
Gemini API Python Error Code Guide — Fixing RESOURCE_EXHAUSTED, SAFETY, INVALID_ARGUMENT in Antigravity Development
A practical guide to fixing common Gemini API Python SDK errors — RESOURCE_EXHAUSTED, SAFETY, INVALID_ARGUMENT, and DEADLINE_EXCEEDED — with real code examples for developers building with Antigravity.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →