◉GEMINI LABJP
●2.5 ROUTE — From today, 12/1, calls to gemini-2.5-pro and 2.5-flash are rerouted to newer models automatically●CLI 0.71.1 — Gemini CLI stable is still v0.71.1, with a 0.73 nightly published on 11/30●INTRO END — Introductory pricing for 3.8, 3.7 and 3.6 Flash ends on 12/31. 30 days left●VERTEX — Developers are asking how to run Gemini CLI with Vertex AI credentials●NEON — Gemini 4 Neon became generally available on 11/18 (paid tier only)●IMAGE TEXT — A new test shows text inside an image can sway Gemini's answer●2.5 ROUTE — From today, 12/1, calls to gemini-2.5-pro and 2.5-flash are rerouted to newer models automatically●CLI 0.71.1 — Gemini CLI stable is still v0.71.1, with a 0.73 nightly published on 11/30●INTRO END — Introductory pricing for 3.8, 3.7 and 3.6 Flash ends on 12/31. 30 days left●VERTEX — Developers are asking how to run Gemini CLI with Vertex AI credentials●NEON — Gemini 4 Neon became generally available on 11/18 (paid tier only)●IMAGE TEXT — A new test shows text inside an image can sway Gemini's answer
Articles/Gemini Basics
◉ Gemini Basics/2026-05-04Advanced

Gemini 3.2 in Production: A Playbook for Model Selection, Cost Optimization, and Implementation Patterns

How I run Gemini 3.2 inside a shipping app: where I draw the line between Pro, Flash and Nano, patterns for streaming, function calling and multimodal input, the order in which I cut costs, and what I retry and monitor.

gemini121gemini 3.2google aiproduction140api12cost optimization8implementation patterns

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 usageMetadata and 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:

  1. Least privilege. Split read-only from writable functions, and put a human confirmation in front of anything that writes.
  2. A call cap. Set a hard limit, around ten calls per session, in case the model keeps calling.
  3. 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.

  1. Error rate: notify when it passes 5% over a five-minute window. Count it in the app as well as on Google's dashboard.
  2. Average latency: investigate when Flash stays above one second or Pro above five.
  3. Daily cost: catch a spike the same day, against the prior seven-day average.
  4. 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.

Share

Thank You for Reading

Gemini 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

◈ API / SDK2026-04-01
Growing a Customer Support Chatbot with Gemini API: An Implementation Notebook
An implementation notebook for building a production-ready customer support chatbot with Gemini API, covering three-layer system prompts, Function Calling for FAQ lookup, escalation design, and seven pitfalls not covered in the official documentation, drawn from indie developer experience.
◉ Gemini Basics2026-10-18
Working Solo: Pay for Google AI Pro or Workspace Standard?
A three-question way for freelancers and one-person businesses to choose between Google AI Pro and Workspace Business Standard: custom-domain email, where Gemini shows up in your apps, and how heavily you use it. Based on the official pricing pages.
◉ Gemini Basics2026-10-13
When Gemini's Activity Setting Won't Change on a Work Account: Three Screens to Check First
If the Gemini app's Activity setting doesn't behave on a work or school account, check three places in order: your own screen, the admin console, and Vault. Includes a short message to send your admin and a line to draw before pasting customer details.