Skip to content

Connect to Gemini from Python

A working Python script that authenticates with the Google Gemini API and returns a generated response. By the end you will have the SDK installed, your key stored safely, and patterns for text, streaming, and multimodal (image + text) requests.

Requirement Notes
Python 3.9+ With an active virtual environment
Gemini API key Create one at AI Studio
pip Comes with Python
Terminal window
python -m pip install google-genai python-dotenv

Google’s current recommended package is google-genai (the Google GenAI SDK). Older tutorials may reference google-generativeai — that package is still available but the newer SDK is the recommended path for new code.

Terminal window
# macOS / Linux
export GEMINI_API_KEY="AIzaSy-your-key-here"
# Windows PowerShell
$env:GEMINI_API_KEY = "AIzaSy-your-key-here"

.env file for local development (add .env to .gitignore):

GEMINI_API_KEY=AIzaSy-your-key-here

Save as gemini_test.py and run with python gemini_test.py (Python 3.9+):

import os
from dotenv import load_dotenv
from google import genai
load_dotenv()
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain retrieval-augmented generation in two short sentences.",
)
print(response.text)

A 401 UNAUTHENTICATED error means the key is missing or wrong. A 404 Not Found on the model name means the model ID is incorrect — check the Google Models guide for current names.

For real-time output in chat applications or long responses:

from google import genai
import os
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
for chunk in client.models.generate_content_stream(
model="gemini-2.5-flash",
contents="List five Python best practices.",
):
if chunk.text:
print(chunk.text, end="", flush=True)
print()

Maintain conversation history by passing previous messages:

from google import genai
from google.genai import types
import os
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
chat = client.chats.create(model="gemini-2.5-flash")
# First turn
response = chat.send_message("My order ORD-001 hasn't arrived. It's been 7 days.")
print(response.text)
# Second turn — model remembers the previous message
response = chat.send_message("What should I do next?")
print(response.text)

Gemini is natively multimodal. Send an image alongside text:

from google import genai
from pathlib import Path
import os
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
image_bytes = Path("invoice.jpg").read_bytes()
response = client.models.generate_content(
model="gemini-2.5-pro",
contents=[
{
"inline_data": {
"mime_type": "image/jpeg",
"data": image_bytes,
}
},
"Extract all line items and amounts from this invoice.",
],
)
print(response.text)
Model Context Best for
gemini-2.5-pro 1 M tokens Complex reasoning, long documents
gemini-2.5-flash 1 M tokens Fast general-purpose tasks
gemini-2.0-flash 1 M tokens High-volume applications

Check the Google Models guide for current model IDs and pricing.

  • Using an outdated package name. google-generativeai is older; use google-genai for new projects.
  • Hardcoding the API key. Use an environment variable — never commit it to source control.
  • Using an outdated model name. Google updates model IDs regularly. Treat the model name as a configuration value, not a constant.
  • Not handling quota errors. The free tier has request limits. Add retry logic with backoff for production:
import time
from google.genai import errors
def call_with_retry(client, prompt: str, retries: int = 3) -> str:
for attempt in range(retries):
try:
resp = client.models.generate_content(
model="gemini-2.5-flash",
contents=prompt,
)
return resp.text
except errors.ClientError as e:
if "RESOURCE_EXHAUSTED" in str(e) and attempt < retries - 1:
time.sleep(2 ** attempt)
else:
raise
return ""