The week I started handing review classification for my wallpaper app to Gemini, I opened the billing page and my stomach dropped. A batch I'd run "just to check it works" had gone entirely through Pro. The code was correct. My choice of model was the mistake.
There's no shortage of feature overviews. What I found much thinner was the material on living with the API day after day inside a real app, so this is the set of lines I drew the slow way: model choice, implementation, cost, and monitoring.
Treat the Models as Roles, Not Ranks
What I'd like to say first is that Pro, Flash and Nano are easier to run when you read them as different jobs rather than a ladder of quality.
Pro handles deep reasoning and long context. Flash is the fast, cheap workhorse. Nano is for work you want to finish on the device. Try to make one model do everything and either cost or latency gives out first. I started with Pro for everything, which is how I ended up staring at that billing page.
One caveat: for generation-to-generation differences (function-calling stability, token consumption and so on), I wouldn't trust release notes alone. Measure with your own prompts and your own images once. My numbers may not carry over to your setup.
Three Questions for Picking a Model
When I can't decide, I ask these in order.
First: does the output reach the user as-is? If so, Pro is the candidate. Internal work like summarizing, classifying and extracting is usually fine on Flash. Nano only comes in when something must stay on the device.
Second: how long can the caller wait? Under a second, Flash. A few seconds, either.
Third: how tight is the monthly cap? If tight, make Flash the default and escalate only where it pays off.
My current assignments:
- Review and inquiry classification (batch): Flash
- In-app chat (real time): Flash by default, Pro for the hard questions
- Long drafts that need real reasoning: Pro
- Simple offline assistance: Nano
Run a new use case through the three questions and the answer usually falls out mechanically.
Don't Hard-Code Model Names
Here's one failure worth admitting.
My first implementation scattered names like gemini-3.2-flash across every call site. When the model generation changed, I missed a replacement, and one batch kept running on the old model for days.
Since then, model names live in exactly one place.
// models.ts — the only place model names appear
export const MODELS = {
fast: process.env.GEMINI_MODEL_FAST ?? 'gemini-3.2-flash',
deep: process.env.GEMINI_MODEL_DEEP ?? 'gemini-3.2-pro',
} as const;Call sites just say MODELS.fast. A generation change becomes an environment-variable swap.
Streaming
Almost every real-time path I build uses streaming. The basic shape:
import { GoogleGenerativeAI } from '@google/generative-ai';
import { MODELS } from './models';
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
async function streamResponse(userPrompt: string): Promise<void> {
const model = genAI.getGenerativeModel({ model: MODELS.fast });
const result = await model.generateContentStream(userPrompt);
for await (const chunk of result.stream) {
process.stdout.write(chunk.text());
}
}For production I add three things:
- A timeout. If output stalls for around 30 seconds, cut it off rather than wait forever.
- Buffering. Don't push one character at a time; batch for a few hundred milliseconds before sending to the client.
- Usage logging. After completion, read
usageMetadataand log token consumption.
The third is unglamorous, but it's the evidence for every cost decision later. Without it you can't tell what to trim.
Mind the SDK Generation, Too
The code above uses @google/generative-ai. That package is the older SDK; new features and fixes land in its successor, @google/genai. I once left it alone because it still worked, and then lost an afternoon translating every new sample into the older style.
For a fresh build, the same streaming looks like this.
import { GoogleGenAI } from '@google/genai';
import { MODELS } from './models';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
async function streamResponse(userPrompt: string): Promise<void> {
const stream = await ai.models.generateContentStream({
model: MODELS.fast,
contents: userPrompt,
});
for await (const chunk of stream) {
process.stdout.write(chunk.text ?? '');
}
}Two differences matter: there is no model object (you pass the model name to ai.models), and chunk.text is a property rather than a function. When migrating an existing app, swap the calls from inside thin wrappers like streamResponse first, so the area you need to re-test stays small. Method names and arguments do change, so check the official reference for the current form before you run it.
Function Calling
The structure for letting the model call your own functions:
const model = genAI.getGenerativeModel({
model: MODELS.deep,
tools: [{
functionDeclarations: [{
name: 'searchReviews',
description: 'Search app reviews for relevant entries',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Search query' },
limit: { type: 'number', description: 'Max results (up to 10)' },
},
required: ['query'],
},
}],
}],
});
const chat = model.startChat();
const result = await chat.sendMessage('Show me three recent reviews saying notifications never arrive');
const functionCall = result.response.candidates?.[0]?.content?.parts?.[0]?.functionCall;
if (functionCall) {
const args = functionCall.args as { query: string; limit?: number };
const reviews = await searchReviews(args.query, args.limit ?? 3);
const followup = await chat.sendMessage([{
functionResponse: { name: 'searchReviews', response: { reviews } },
}]);
console.log(followup.response.text());
}Three lines I hold in operation:
- Least privilege. Split read-only from writable functions, and put a human confirmation in front of anything that writes.
- A call cap. Set a hard limit, around ten calls per session, in case the model keeps calling.
- Treat return values as data. If a string pulled from outside contains something that reads like an instruction, the model may follow it. Trim length and shape before handing it back.
The model decides the next step; the authority to execute stays with me. I don't want to loosen that, however complicated the design gets.
Preparing Multimodal Input
Being able to hand over images and PDFs directly is a real strength, but sending them raw shows up on the bill.
import * as fs from 'fs';
async function analyzeImage(imagePath: string, question: string): Promise<string> {
const model = genAI.getGenerativeModel({ model: MODELS.deep });
const imagePart = {
inlineData: {
data: fs.readFileSync(imagePath).toString('base64'),
mimeType: 'image/jpeg',
},
};
const result = await model.generateContent([question, imagePart]);
return result.response.text();
}Before shipping, I revisit three things:
- Downscale first. Large images push token use up. Shrink the long edge with something like Sharp.
- Don't send whole videos. Extract representative frames at scene changes.
- Cross-check PDF readings. Unusual layouts can be misread, so verify anything costly to get wrong, like amounts and dates, by another route.
Working with images in a wallpaper app, I've also hit the opposite problem: shrink too far and the judgment starts to wobble. Measuring once how far you can go before the answer changes turned out to be the shortcut.
The Order I Cut Costs
In order of what worked:
First, route between models
Choose Flash or Pro automatically from input length and question type.
function selectModel(userPrompt: string): string {
const tokens = estimateTokens(userPrompt);
const needsReasoning = /compare|analy[sz]e|why|difference/i.test(userPrompt);
return tokens > 4000 || needsReasoning ? MODELS.deep : MODELS.fast;
}A regex is a crude judge. Even so, my monthly bill dropped noticeably compared with the period when everything ran on Pro. The size of the saving depends heavily on the workload, so compare against your own usage logs first.
Second, reuse answers to repeated questions
Where similar questions recur, reuse earlier responses: compare by embedding similarity and reuse above a threshold. If the underlying information changes, keep the lifetime short (hours to a day), or you'll keep serving stale answers.
Last, trim the prompt
More reference material doesn't always mean a better answer. Passing five summarized documents instead of twenty full ones often kept quality intact with much less input. Include only what's truly needed.
Using Gemini Alongside Other Models
Benchmark numbers matter less than how a model feels on your own task. My tendencies:
- Gemini: long-context reading, handling images and PDFs together, multilingual translation
- Claude: structuring long text, reading and explaining existing code
- Other models: complex agent-style tasks, tried case by case
Claude for prose, Gemini for image analysis and multilingual work, and I keep both rather than collapsing to one. Dividing by role settled both bill and quality better than picking a single winner.
An Example: Classifying Reviews
I give a Flash model the job of labeling app reviews. The key was fixing the output to JSON.
const model = genAI.getGenerativeModel({
model: MODELS.fast,
generationConfig: {
responseMimeType: 'application/json',
responseSchema: {
type: 'object',
properties: {
kind: { type: 'string', enum: ['bug', 'request', 'praise', 'other'] },
topics: { type: 'array', items: { type: 'string' }, maxItems: 5 },
confidence: { type: 'number', minimum: 0, maximum: 1 },
},
required: ['kind', 'topics', 'confidence'],
},
},
});
const result = await model.generateContent(`Classify this review:\n\n${reviewText}`);
const classification = JSON.parse(result.response.text());Anything under 0.7 confidence goes into a queue I check by eye. Separating what's automated from what I look at myself kept me from trusting the classifier too much.
Errors and Retries
In production, a certain share of calls will fail. Separate what's worth retrying from what isn't.
async function callWithRetry<T>(
fn: () => Promise<T>,
maxRetries = 3,
initialDelay = 1000
): Promise<T> {
let lastError: unknown;
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (e) {
lastError = e;
if (!isRetryableError(e) || i === maxRetries - 1) throw e;
await new Promise(r => setTimeout(r, initialDelay * 2 ** i));
}
}
throw lastError;
}
function isRetryableError(e: any): boolean {
const status = e?.status ?? e?.response?.status;
return [429, 500, 502, 503, 504].includes(status);
}Retry 429 and 5xx with exponential backoff. Fail fast on other 4xx, since retrying won't change the result. I once retried a 404 (a wrong model name) and filled the logs with the same error.
What I Watch, in Order
Deciding the order ahead of time keeps me from panicking.
- Error rate: notify when it passes 5% over a five-minute window. Count it in the app as well as on Google's dashboard.
- Average latency: investigate when Flash stays above one second or Pro above five.
- Daily cost: catch a spike the same day, against the prior seven-day average.
- Routing mix: if the Flash-to-Pro ratio differs from expectations, either the routing is broken or the inputs have shifted.
Closing
I read Gemini 3.2 less as a model that aims to win everywhere and more as one that leans into long context, multimodal input and Google-service integration. So rather than abandoning other models, dividing work by role has been calmer in my operation.
If you'd like a first step, gather model names into one place and log usageMetadata in a single line. That's where I started.