Google AI Studio (Gemini API) Integration Guide
Gemini API Developer Portal
Every model, endpoint, and price — audited Jul 15, 2026
What is the Gemini API?
gemini-3.5-flash at $1.50/$9.00 per 1M tokens, 1M context, function-call ids, and a fast-rotating model lineup.
Production notes from the July 2026 audit: keep temperature at 1.0 on Gemini 3 models (lowering it degrades reasoning); always echo the function-call id in your functionResponse; iterate the parts array instead of assuming position. The lineup rotates hard — the entire 2.0 family shut down June 1 and Veo 3 GA June 30, so pin dated model strings and watch the deprecations page. Batch/Flex halve costs; context caching drops 3.5 Flash input to $0.15/1M. For codeAmani, Gemini stays the secondary provider: multimodal workhorse and thumbnail generator, while Claude handles primary reasoning. Full model/pricing detail lives in the interactive portal at /portal/gemini.
Five Gemini primitives
One API key spans frontier text models, a media studio, real-time voice, and grounded tools.
██████╗ ██████╗ ██████╗ ██████╗ ██╗ ███████╗ █████╗ ██╗
██╔════╝ ██╔═══██╗██╔═══██╗██╔════╝ ██║ ██╔════╝ ██╔══██╗██║
██║ ███╗██║ ██║██║ ██║██║ ███╗██║ █████╗ ███████║██║
██║ ██║██║ ██║██║ ██║██║ ██║██║ ██╔══╝ ██╔══██║██║
╚██████╔╝╚██████╔╝╚██████╔╝╚██████╔╝███████╗███████╗ ██║ ██║██║
╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝╚═╝
███████╗████████╗██╗ ██╗██████╗ ██╗ ██████╗
██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║██╔═══██╗
███████╗ ██║ ██║ ██║██║ ██║██║██║ ██║
╚════██║ ██║ ██║ ██║██║ ██║██║██║ ██║
███████║ ██║ ╚██████╔╝██████╔╝██║╚██████╔╝
╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝Google AI Studio (Gemini API) Integration Guide
Focus: Google AI Studio is where codeAmani Labs creates its Gemini API key. The Gemini API powers text, multimodal, and image generation (it generates the dashboard's tech-stack thumbnails). This is the AI Studio / Developer-API path — distinct from Vertex AI.
Overview
🧭 Interactive portal: the dashboard ships a full-page Gemini developer portal — every model, endpoint, and price, audited against ai.google.dev on 2026-07-15.
Here's the high-level path your call takes — once you picture it, the rest of the guide clicks into place.
Google AI Studio issues a Gemini Developer API key
that authenticates calls to generativelanguage.googleapis.com. The official, current
SDK is @google/genai (JS/TS) and google-genai (Python). The older
@google/generative-ai package is deprecated — do not use it for new code.
Official Documentation
| Resource | URL |
|---|---|
| Gemini API docs | https://ai.google.dev/gemini-api/docs |
| Get an API key | https://ai.google.dev/gemini-api/docs/api-key |
| Google AI Studio | https://aistudio.google.com |
JS SDK (@google/genai) | https://googleapis.github.io/js-genai/ |
Python SDK (google-genai) | https://googleapis.github.io/python-genai/ |
| Image generation | https://ai.google.dev/gemini-api/docs/image-generation |
| Rate limits & tiers | https://ai.google.dev/gemini-api/docs/rate-limits |
| Error codes / troubleshooting | https://ai.google.dev/gemini-api/docs/troubleshooting |
1. Get an API key
- Go to Google AI Studio and sign in.
- Select Get API key → Create API key (in a Google Cloud project).
- Store it as
GEMINI_API_KEY(the SDK also readsGOOGLE_API_KEY).- codeAmani convention:
.env.local(gitignored) for local dev + the Vercel project's env vars for deploys. Server-side only — never ship the key to the browser.
- codeAmani convention:
A Maps Platform API key is NOT a Gemini key: calling the Gemini API with one returns
403 API_KEY_SERVICE_BLOCKED. Use a key created in AI Studio.
2. Install the SDK
npm install @google/genai # JS/TS
pip install google-genai # Python3. Generate text
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const res = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain M-Pesa STK Push in one sentence.",
});
console.log(res.text);4. Generate images
You have two solid routes to an image — this map makes choosing easy.
Two options. Imagen (dedicated image model):
const res = await ai.models.generateImages({
model: "imagen-4.0-generate-001",
prompt: "A glossy 3D emblem of a green database with a lightning bolt",
config: { numberOfImages: 1 },
});
const bytes = res.generatedImages?.[0]?.image?.imageBytes; // base64Gemini multimodal image (gemini-2.5-flash-image) via REST — used by this repo's
scripts/generate-thumbnails.py to build the card thumbnails:
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" -H "Content-Type: application/json" \
-d '{"contents":[{"parts":[{"text":"A colorful app-icon logo"}]}]}'
# response: candidates[].content.parts[].inlineData.data (base64 PNG)Models (verified available on the AI Studio key)
| Model | Use |
|---|---|
gemini-2.5-flash | fast text / multimodal reasoning |
gemini-2.5-flash-image | image generation + editing ("nano banana") |
imagen-4.0-generate-001 / -fast- / -ultra- | high-quality text-to-image (Imagen 4) |
gemini-3-pro-image-preview | preview high-end image model |
List live models for a key:
GET https://generativelanguage.googleapis.com/v1beta/models with header
x-goog-api-key: $GEMINI_API_KEY.
Errors, rate limits & retries
The Gemini API returns standard HTTP codes with a canonical status name. The ones worth retrying are transient (rate limit + server-side); the rest are bugs in your request and retrying just wastes quota.
| Code | Status | Meaning | Retry? |
|---|---|---|---|
400 | INVALID_ARGUMENT | malformed request / bad field | No — fix the call |
403 | PERMISSION_DENIED | wrong/blocked key (e.g. a Maps key) | No — fix the key |
429 | RESOURCE_EXHAUSTED | you exceeded the rate limit / quota | Yes — backoff |
500 | INTERNAL | unexpected error on Google's side | Yes — backoff |
503 | UNAVAILABLE | service temporarily overloaded / down | Yes — backoff |
504 | DEADLINE_EXCEEDED | request didn't finish in time | Raise client timeout / shrink prompt |
Authoritative tables: the troubleshooting page (error codes) and the rate-limits page (tiers). The official docs do not prescribe a backoff algorithm, so the snippet below is a standard exponential-backoff-with-jitter pattern applied to the documented retryable codes.
The @google/genai SDK throws an ApiError that extends Error with a .status
field holding the HTTP code — so you branch on .status, not on string matching.
import { GoogleGenAI, ApiError } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const RETRYABLE = new Set([429, 500, 503]); // RESOURCE_EXHAUSTED, INTERNAL, UNAVAILABLE
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** Run a Gemini call with exponential backoff + jitter on transient errors. */
async function withBackoff<T>(fn: () => Promise<T>, maxRetries = 5): Promise<T> {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
const status = err instanceof ApiError ? err.status : undefined;
if (attempt >= maxRetries || status === undefined || !RETRYABLE.has(status)) {
throw err; // out of retries, or a non-retryable error like 400/403
}
// 1s, 2s, 4s, 8s ... capped at 30s, plus up to 1s of jitter
const delay = Math.min(2 ** attempt * 1000, 30_000) + Math.random() * 1000;
await sleep(delay);
}
}
}
const res = await withBackoff(() =>
ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain M-Pesa STK Push in one sentence.",
}),
);
console.log(res.text);Free tier vs paid. The free tier has tight per-minute and per-day quotas; once you enable billing your project moves to a paid usage tier with much higher limits. Exact RPM/TPD/RPD numbers vary by model and tier and change over time, so do not hard-code them — read your project's live limits in Google AI Studio and on the rate-limits page. For the thumbnail pipeline, image generation is metered separately and per-image, so a single 429 burst on the free tier is common — backoff plus caching in R2 keeps it cheap.
Gotcha: retrying a
400/403is pointless and, with a429, a tight retry loop with no backoff just digs the quota hole deeper — each rejected call can still count against your rate budget. Only retry the codes in the table above, always with growing delays, and cap total attempts.
codeAmani notes
- AI routing: Gemini is the image/multimodal provider here; Anthropic Claude remains
primary for reasoning/codegen (see
AI_WORKFLOWS.md). - Security: keep
GEMINI_API_KEYserver-side; call from API routes / scripts, never inline in client components. Restrict the key in Google Cloud where possible. - Cost: image generation is billed per image — generate thumbnails once and cache
them (this repo stores them in the
tech-stack-bucketR2 bucket).