Connect to Gemini from Python
What you’ll build
Section titled “What you’ll build”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.
Prerequisites
Section titled “Prerequisites”| Requirement | Notes |
|---|---|
| Python 3.9+ | With an active virtual environment |
| Gemini API key | Create one at AI Studio |
pip |
Comes with Python |
Step 1 — Install the SDK
Section titled “Step 1 — Install the SDK”python -m pip install google-genai python-dotenvGoogle’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.
Step 2 — Store the API key
Section titled “Step 2 — Store the API key”# macOS / Linuxexport 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-hereStep 3 — Make a first request
Section titled “Step 3 — Make a first request”Save as gemini_test.py and run with python gemini_test.py (Python 3.9+):
import osfrom dotenv import load_dotenvfrom 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.
Step 4 — Streaming responses
Section titled “Step 4 — Streaming responses”For real-time output in chat applications or long responses:
from google import genaiimport 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()Step 5 — Multi-turn conversation
Section titled “Step 5 — Multi-turn conversation”Maintain conversation history by passing previous messages:
from google import genaifrom google.genai import typesimport os
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
chat = client.chats.create(model="gemini-2.5-flash")
# First turnresponse = chat.send_message("My order ORD-001 hasn't arrived. It's been 7 days.")print(response.text)
# Second turn — model remembers the previous messageresponse = chat.send_message("What should I do next?")print(response.text)Step 6 — Multimodal: image + text
Section titled “Step 6 — Multimodal: image + text”Gemini is natively multimodal. Send an image alongside text:
from google import genaifrom pathlib import Pathimport 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)Available models
Section titled “Available models”| 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.
Common mistakes
Section titled “Common mistakes”- Using an outdated package name.
google-generativeaiis older; usegoogle-genaifor 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 timefrom 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 ""Related pages
Section titled “Related pages”- Google Gemini API key guide — creating and securing your key
- Google Models guide — Gemini model family, context windows, pricing
- Connect to OpenAI from Python — same pattern for OpenAI
- Python AI packages — full AI/ML package ecosystem
Official references
Section titled “Official references”- Google GenAI SDK on GitHub —
google-genaipackage - Gemini API documentation — REST and SDK reference
- Google AI Studio — model playground and API key management