●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
Building AI-Powered iOS and Android Apps with the Gemini API — Image Recognition, Voice Analysis, Chat, and Monetization
Architecture, working code, and monetization for adding image recognition, voice analysis, and AI chat to iOS/Android apps — rewritten in November 2026 for @google/genai and gemini-4-hydrogen, with an error triage table, a cost formula, and API key restriction checks.
Setup and context — Where the API Call Lives Decides Everything After
The night I tried to bolt image tagging onto my wallpaper app, I got a prototype working by calling Gemini straight from the client. The next morning I unpacked that test build to look inside, found the key sitting there as a plain string, and just stopped for a while. I'd been so relieved that it worked that I never made the placement decision at all.
Understanding images, listening to audio, holding a conversation with context — an indie developer can wire all of that up with one API today. That is exactly why the first architecture call matters: get it wrong and you rebuild for cost and security later.
When I first retrofitted AI features into one of my own apps as an indie developer, the hardest question was not the implementation itself — it was where the API call should live. Call Gemini directly from the client, or route everything through a proxy? Get that decision wrong and you end up rebuilding for both cost and security reasons later. This article works through that decision for iOS (Swift) and Android (Kotlin), then moves on to concrete code, cost optimization, privacy, and monetization, in the order you would actually build a production app. Keys live on the server; models are routed per feature. Every code sample below sits on that line.
This article assumes you have iOS or Android development experience and a basic familiarity with the Gemini API. Each code sample starts with what it solves, so you can follow along even if you've never integrated an AI API before.
Three Things to Rewrite First (as of November 2026)
I published this in July 2026 and reworked it in November. These are the three patterns you are most likely to inherit from older samples — all checked against official sources as of November 2026.
Item
Old pattern
Current pattern
Why
Node.js SDK
GoogleGenerativeAI from @google/generative-ai
GoogleGenAI from @google/genai (ai.models.generateContent)
The old repo was renamed to deprecated-generative-ai-js and is marked deprecated
Gemini API changelog. Several forum reports describe 2.5 Flash returning 404 before its announced shutdown date
Firebase Functions
runWith via import * as functions from "firebase-functions"
Import from firebase-functions/v1 if you keep the 1st-gen style
Since firebase-functions v6 the top-level default is the 2nd-gen API
One misconception worth correcting up front: swapping the model name does not finish the migration. The new SDK also changes how you read the response (result.response.text() becomes response.text) and how chat history is passed. All code below uses the new SDK.
Chapter 1: Designing Your Mobile AI Architecture
Server-Side vs. On-Device — Making the Right Call
The first design decision you'll face is whether to process AI workloads server-side via the Gemini API, or on-device using a local model like Gemma. Each has clear strengths.
Choose Gemini API (server-side) when:
High accuracy image, video, or audio analysis is required
Conversations involve long context windows (1,000+ tokens)
You need multimodal input (image + text combinations)
You want to monetize the AI feature as a premium offering
You need model updates to reach users instantly
Choose on-device processing when:
Offline functionality is non-negotiable
You need ultra-low latency for real-time interactions
Privacy requirements prevent sending data to a server
The task is lightweight — simple text classification, basic sentiment
Most production apps benefit from a hybrid approach: handle lightweight tasks on-device and reach out to the Gemini API only for complex analysis. This controls costs while keeping the user experience smooth.
Recommended Architecture for Indie Developers
Here is a clean, scalable architecture that works well for solo developers.
[Mobile App]
↓ HTTPS (certificate pinning)
[Backend API Server] ← Firebase Functions / Cloudflare Workers
↓ API key (server-held — never in the app binary)
[Gemini API]
↓
[Response processing]
↓
[Mobile App (display)]
Critical rule: Never embed your API key in your app binary. Both App Store and Play Store apps can be reverse-engineered, and an exposed key will be abused. Always route through a backend proxy that validates authenticated user requests before forwarding to the Gemini API.
Firebase Backend Setup
Firebase Functions combined with Firebase Authentication gives indie developers a secure, low-cost backend that scales automatically.
// Firebase Functions: gemini-proxy.ts// deps: npm i @google/genai firebase-functions firebase-adminimport * as functions from "firebase-functions/v1"; // v1 import keeps the 1st-gen runWith APIimport * as admin from "firebase-admin";import { GoogleGenAI } from "@google/genai";admin.initializeApp();const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY! });const MODEL = process.env.GEMINI_MODEL ?? "gemini-4-hydrogen"; // keep the model swappable via envexport const analyzeImage = functions .runWith({ memory: "512MB", timeoutSeconds: 60 }) .https.onCall(async (data, context) => { // Reject unauthenticated requests if (!context.auth) { throw new functions.https.HttpsError( "unauthenticated", "Authentication required" ); } const { imageBase64, prompt } = data; const response = await ai.models.generateContent({ model: MODEL, contents: [ { role: "user", parts: [ { inlineData: { data: imageBase64, mimeType: "image/jpeg" } }, { text: prompt }, ], }, ], }); // The new SDK exposes text as a property, not a method return { text: response.text ?? "" }; });
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Architecture decisions and working code for unifying image, voice, and chat behind a single proxy
✦A formula that turns DAU and call counts into a monthly bill, plus real numbers from routing classification calls to a lighter model
✦A five-item pre-release checklist for the mandatory API key restriction change from June 2026
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Here is a complete implementation for capturing and analyzing images in an iOS app.
// ImageAnalyzer.swiftimport Foundationimport UIKitclass ImageAnalyzer { private let backendURL = "https://YOUR_REGION-YOUR_PROJECT.cloudfunctions.net/analyzeImage" // Analyze an image and return text results func analyze(image: UIImage, prompt: String) async throws -> String { // Resize to 800px max dimension to reduce token count and cost let resized = resizeImage(image, maxDimension: 800) guard let imageData = resized.jpegData(compressionQuality: 0.7) else { throw AnalyzerError.imageConversionFailed } let base64 = imageData.base64EncodedString() // Get Firebase Auth token let token = try await fetchAuthToken() // Send to backend proxy var request = URLRequest(url: URL(string: backendURL)!) request.httpMethod = "POST" request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "Content-Type") let body: [String: Any] = ["imageBase64": base64, "prompt": prompt] request.httpBody = try JSONSerialization.data(withJSONObject: body) let (data, _) = try await URLSession.shared.data(for: request) let response = try JSONDecoder().decode(AnalysisResponse.self, from: data) return response.text } private func resizeImage(_ image: UIImage, maxDimension: CGFloat) -> UIImage { let size = image.size let ratio = min(maxDimension / size.width, maxDimension / size.height) if ratio >= 1.0 { return image } let newSize = CGSize(width: size.width * ratio, height: size.height * ratio) UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: CGRect(origin: .zero, size: newSize)) let resized = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resized }}struct AnalysisResponse: Codable { let text: String}enum AnalyzerError: Error { case imageConversionFailed}
Android (Kotlin) — CameraX Integration
On Android, CameraX lets you capture frames in real time and feed them to Gemini API for analysis.
// ImageAnalysisViewModel.ktimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.launchimport android.graphics.Bitmapclass ImageAnalysisViewModel( private val geminiRepository: GeminiRepository) : ViewModel() { private val _analysisResult = MutableStateFlow<AnalysisState>(AnalysisState.Idle) val analysisResult: StateFlow<AnalysisState> = _analysisResult fun analyzeImage(bitmap: Bitmap, prompt: String) { viewModelScope.launch { _analysisResult.value = AnalysisState.Loading // Resize to 800px for cost and speed optimization val resized = resizeBitmap(bitmap, 800) geminiRepository.analyzeImage(resized, prompt) .onSuccess { result -> _analysisResult.value = AnalysisState.Success(result) } .onFailure { error -> _analysisResult.value = AnalysisState.Error(error.message ?: "Unknown error") } } } private fun resizeBitmap(bitmap: Bitmap, maxDimension: Int): Bitmap { val ratio = minOf( maxDimension.toFloat() / bitmap.width, maxDimension.toFloat() / bitmap.height ) if (ratio >= 1.0f) return bitmap val newWidth = (bitmap.width * ratio).toInt() val newHeight = (bitmap.height * ratio).toInt() return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true) }}sealed class AnalysisState { object Idle : AnalysisState() object Loading : AnalysisState() data class Success(val result: String) : AnalysisState() data class Error(val message: String) : AnalysisState()}
Practical Use Cases for Camera AI
Concrete app ideas that leverage Gemini API's multimodal capabilities:
Food nutrition analyzer: Photograph a meal to get automatic calorie and nutrient estimates
Text translation lens: Point your camera at a sign or document and get instant translation — no OCR layer needed
Plant and animal identification: Match photos to species names, characteristics, and care tips
Fashion advice: Analyze outfit photos and suggest improvements or pairings
Label and barcode reader: Extract product ingredients, specs, or pricing from photos
Each of these is a natural premium feature users will pay for.
Chapter 3: Voice Analysis Features
Sending Audio Directly to Gemini API
The Gemini API accepts audio files directly as input (Audio Understanding). Supported formats and models change often, so check the official model page before you build on it. You can pass a recorded audio file directly to the API and receive transcription, summarization, emotion analysis, or task extraction — all from a single request.
// VoiceAnalyzer.swift (iOS)import Foundationimport AVFoundationclass VoiceAnalyzer: NSObject, AVAudioRecorderDelegate { private var audioRecorder: AVAudioRecorder? private var recordingURL: URL? // Start recording func startRecording() throws { let session = AVAudioSession.sharedInstance() try session.setCategory(.record, mode: .default) try session.setActive(true) let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] recordingURL = documentsPath.appendingPathComponent("temp_recording.m4a") let settings: [String: Any] = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 44100, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] audioRecorder = try AVAudioRecorder(url: recordingURL!, settings: settings) audioRecorder?.record() } // Stop recording and analyze func stopAndAnalyze(task: String) async throws -> String { audioRecorder?.stop() guard let url = recordingURL else { throw VoiceError.noRecording } let audioData = try Data(contentsOf: url) let base64Audio = audioData.base64EncodedString() // Route through backend proxy to Gemini API return try await sendAudioToBackend( audioBase64: base64Audio, mimeType: "audio/mp4", task: task ) }}enum VoiceError: Error { case noRecording}
Meeting minutes generator: Record a meeting, get structured notes with decisions and action items
Voice journaling: Speak naturally, receive a clean, formatted written entry
Language learning pronunciation coach: Record speech, receive feedback on accuracy and fluency
Customer call sentiment analysis: Automatically score customer support calls
Voice-to-task: Convert spoken to-do items into structured tasks with priorities
Chapter 4: AI Chat Features
Managing Multi-Turn Conversations
The most important design challenge in AI chat is conversation history management. The Gemini API is stateless — you must send the entire conversation history with each request.
// ChatSession.swift (iOS)import Foundationclass ChatSession: ObservableObject { @Published var messages: [ChatMessage] = [] private let backendClient: BackendClient private let systemInstruction: String init( backendClient: BackendClient, systemInstruction: String = "You are a helpful assistant." ) { self.backendClient = backendClient self.systemInstruction = systemInstruction } // Send a message with streaming support func sendMessage(_ text: String) async { let userMessage = ChatMessage(role: "user", content: text) messages.append(userMessage) // Placeholder for the assistant's streaming response let assistantMessage = ChatMessage(role: "assistant", content: "") messages.append(assistantMessage) let assistantIndex = messages.count - 1 do { let stream = try await backendClient.streamChat( history: messages.dropLast(), systemInstruction: systemInstruction ) for try await chunk in stream { await MainActor.run { messages[assistantIndex].content += chunk } } } catch { await MainActor.run { messages[assistantIndex].content = "An error occurred: \(error.localizedDescription)" } } }}struct ChatMessage: Identifiable { let id = UUID() let role: String var content: String}
Backend Streaming Implementation
// Firebase Functions: stream-chat.tsimport * as functions from "firebase-functions/v1";import * as admin from "firebase-admin";import { GoogleGenAI, Content } from "@google/genai";const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY! });export const streamChat = functions.https.onRequest(async (req, res) => { const token = req.headers.authorization?.split("Bearer ")[1]; if (!token) { res.status(401).send("Unauthorized"); return; } await admin.auth().verifyIdToken(token); const { history, systemInstruction } = req.body; // Server-Sent Events headers res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-cache"); res.setHeader("Connection", "keep-alive"); // The last item is this turn's message; pass only earlier turns as history (avoids sending it twice) const past = history.slice(0, -1); const lastMessage: string = history[history.length - 1].content; // Convert history to Gemini API format const geminiHistory: Content[] = past.map((msg: any) => ({ role: msg.role === "assistant" ? "model" : "user", parts: [{ text: msg.content }], })); const chat = ai.chats.create({ model: "gemini-4-hydrogen", config: { systemInstruction }, history: geminiHistory, }); // In the new SDK the return value itself is the async iterator const stream = await chat.sendMessageStream({ message: lastMessage }); for await (const chunk of stream) { const text = chunk.text ?? ""; if (text) res.write(`data: ${JSON.stringify({ text })}\n\n`); } res.write("data: [DONE]\n\n"); res.end();});
Personalized System Prompts
The system prompt is how you give your chat AI a distinct personality and purpose. Injecting user profile data into the system prompt is a powerful and underused technique.
// personalized-system-prompt.tsfunction buildSystemPrompt(userProfile: UserProfile): string { return `You are a personal AI assistant for ${userProfile.name}.User context:- Language preference: ${userProfile.language}- Expertise level: ${userProfile.level} (beginner/intermediate/expert)- Interests: ${userProfile.interests.join(", ")}- Previous interaction count: ${userProfile.interactionCount}Guidelines:- Respond in ${userProfile.language}- Adjust complexity to their ${userProfile.level} level- Reference their interests when genuinely relevant- Be concise: maximum 3 paragraphs unless asked for detail- Never request personal information`;}
Chapter 5: Cost Optimization Strategies
Cost is the part that keeps me up at night. Early on I sent every feature to the same model and only thought about routing after the first bill arrived. How much you save depends heavily on your feature mix, so rather than promise a percentage, here is the order I'd tackle things in.
Strategy 1: Model Tiering
Not every task needs the most capable model. Matching model to task complexity is the single highest-impact optimization.
// model-selector.ts// IDs as of November 2026. Upper-tier pricing keeps changing, so keep it swappable via envtype TaskType = "sentiment" | "classification" | "chat" | "image" | "long_document";type ModelTier = "lite" | "main" | "heavy";const MODEL_MAP: Record<ModelTier, string> = { lite: "gemini-3.5-flash-lite", // classification, short summaries main: "gemini-4-hydrogen", // chat and image description heavy: process.env.GEMINI_HEAVY_MODEL ?? "gemini-4-hydrogen", // long context / hard reasoning (change only this line)};function selectModel(task: TaskType, contextTokens: number): string { // Fixed-shape answers are fine on lite if (task === "sentiment" || task === "classification") return MODEL_MAP.lite; // Send only long documents or heavy reasoning to heavy if (task === "long_document" || contextTokens > 100_000) return MODEL_MAP.heavy; return MODEL_MAP.main;}// e.g. selectModel("classification", 300) → "gemini-3.5-flash-lite"
Strategy 2: Response Caching
Cache identical or near-identical requests to avoid redundant API calls.
// image-optimizer.tsfunction getTargetResolution(purpose: string): number { const resolutionMap: Record<string, number> = { "ocr": 1200, // Text recognition needs higher resolution "object-detect": 800, // Object detection works at medium resolution "thumbnail": 400, // Thumbnail analysis is fine at low resolution "default": 600, }; return resolutionMap[purpose] ?? resolutionMap["default"];}// Apply resizing before base64 encoding to reduce token count significantly
Strategy 4: Async Batch Processing
I misunderstood this for a long time. Running requests in parallel is not the same as using the Batch API. The code below sends requests at normal price with a concurrency cap — more throughput, same unit cost. To actually lower the unit price for non-real-time work (overnight tagging, say), submit it through the official Batch API (batch mode), which is billed at half the standard rate and returns results asynchronously rather than immediately (as of November 2026; confirm on the official pricing page).
# batch_processor.py# deps: pip install google-genai (reads the key from GEMINI_API_KEY)import asynciofrom typing import List, Dictfrom google import genaifrom google.genai import typesclient = genai.Client()async def process_batch(items: List[Dict]) -> List[str]: """Process items in parallel with a concurrency cap (normal price; use the Batch API to cut unit cost)""" async def process_single(item: Dict) -> str: response = await client.aio.models.generate_content( model="gemini-3.5-flash-lite", contents=item["prompt"], config=types.GenerateContentConfig( max_output_tokens=512, # Limit output tokens temperature=0.7, ), ) return response.text or "" # Max 5 concurrent requests to respect rate limits semaphore = asyncio.Semaphore(5) async def bounded_process(item: Dict) -> str: async with semaphore: return await process_single(item) results = await asyncio.gather(*[bounded_process(item) for item in items]) return list(results)# Example usage:# items = [{"prompt": "Summarize: ..."}, {"prompt": "Translate: ..."}]# Expected output: ["Summary text", "Translated text"]
Estimate Cost From Your Own Assumptions (November 2026)
This section used to list dollar figures per DAU tier, and they went stale every time models and prices rotated. Now I keep the formula instead.
Here are worked examples on the gemini-4-hydrogen paid tier ($1.50 input / $7.50 output per 1M tokens). The token counts are placeholders — measure your own requests with count_tokens and substitute.
Scenario
Calls per day
Per-call assumption
Cost per call
Monthly estimate
1,000 DAU, 1 image analysis/day
1,000
1,500 input / 300 output tokens
~$0.0045
~$135
Same job routed to lite
1,000
Same
Recalculate at lite pricing
Check the official pricing page
10,000 DAU, 5 chat turns/day
50,000
2,000 input (with history) / 250 output tokens
~$0.0049
~$7,300
The chat row is the one that surprised me. Conversation resends history every turn, so the input side balloons. Trim history to the last few turns, replace older turns with a summary, or cap free-plan turns — without one of those three, the bill grows faster than your DAU does. Lite pricing has been revised repeatedly, so I point to the official page instead of printing a number.
Chapter 6: Security and Privacy
Protecting Your API Key
// secure-proxy.tsimport { GoogleGenAI } from "@google/genai";// ✅ Correct: API key stored only on the serverconst ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY! });// ❌ Never do this: API keys in client code are exposed during reverse engineering// const API_KEY = "YOUR_API_KEY"; // GitHub will flag this with Secret Scanning
Sanitizing User Data Before Sending to the API
// PrivacyManager.swift (iOS)class PrivacyManager { // Mask PII before sending to the API static func sanitizeForAPI(_ text: String) -> String { var sanitized = text // Mask email addresses let emailPattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" sanitized = sanitized.replacingOccurrences( of: emailPattern, with: "[EMAIL]", options: .regularExpression ) // Mask phone numbers let phonePattern = "\\d{2,4}-\\d{2,4}-\\d{4}" sanitized = sanitized.replacingOccurrences( of: phonePattern, with: "[PHONE]", options: .regularExpression ) return sanitized }}
Per-User Rate Limiting
Protect against API abuse from malicious users with per-user rate limiting at the backend.
Let users experience the value first: Provide the full experience until the limit is hit, then show the upgrade prompt at the moment of frustration
Frame limits positively: "You have 2 AI analyses left today" is better than "You've used 3 of your 5 free analyses"
Upgrade prompt timing: Show the paywall exactly when the user attempts to use a feature — pair it with a clear statement of value
Annual plan discount: Price the annual plan below twelve months of monthly, and give something back to the people who stay
// PurchaseManager.swift (StoreKit 2)import StoreKitclass PurchaseManager: ObservableObject { @Published var subscriptionStatus: SubscriptionStatus = .free func purchaseSubscription(_ product: Product) async throws { let result = try await product.purchase() switch result { case .success(let verification): let transaction = try checkVerified(verification) await updateSubscriptionStatus() await transaction.finish() case .userCancelled: break case .pending: break @unknown default: break } } func canUseFeature(_ feature: AIFeature) -> Bool { switch (subscriptionStatus, feature) { case (.free, .basicChat): return remainingFreeRequests > 0 case (.standard, _), (.premium, _): return true default: return false } }}
Chapter 8: Troubleshooting Common Issues
With a mobile-to-proxy setup, errors can come from three places: the app, the proxy, or the Gemini API. Use this table to locate the layer first, then go to the specific fix below.
Symptom
Likely cause
How to check
Fix
404 NOT_FOUND (models/... is not found)
Calling a retired or renamed model ID
Check the model name in proxy logs against models.list
Move the model name to an env var and switch to a current ID
429 RESOURCE_EXHAUSTED
Rate limit, daily cap, or free-tier limit: 0
Quota name in the error body and the AI Studio usage page
Exponential backoff plus per-user limits; paid tier if needed
400 INVALID_ARGUMENT on image upload
MIME mismatch, corrupted Base64, or size over limit
Log the first bytes and mimeType just before sending
Convert to JPEG and downscale on device
403 PERMISSION_DENIED
Key restrictions (API / origin) don't match the proxy
Key settings in Google Cloud Console vs. the proxy's origin
Align key restrictions with the proxy
Stream arrives all at once in production, or cuts off
Hosting-layer buffering or timeouts
Compare the same request locally and in production
Review SSE headers and timeouts (Q3)
Q1: "RESOURCE_EXHAUSTED" errors keep appearing
Symptom: Gemini API returns 429 RESOURCE_EXHAUSTED
Cause: You've hit your rate limit (requests per minute or daily token quota)
Solutions:
Implement Exponential Backoff to retry automatically
Use Flash Lite for lightweight tasks to preserve quota headroom
Symptom: The API returns vague or incorrect results for images
Causes and fixes:
Resolution too low: Ensure images are at least 400 × 400px
JPEG quality too low: Set compression quality to 0.7 or higher
Vague prompt: Instead of "analyze this image," try "estimate the calorie count for the food visible in this photo"
Blurry or dark image: Add a pre-flight sharpness/brightness check and prompt the user to retake
Q3: Streaming disconnects mid-response
Symptom: Long AI responses are cut off partway through
Solutions:
For 1st-gen HTTP functions, raise the timeout to the 540-second ceiling
On the mobile side, re-request from the last received position when the stream drops
For responses that are inherently long, use async background jobs instead of streaming
Q4: App Store review flagged my AI content disclosures
Symptom: Review team notes that AI-generated content isn't properly disclosed
Solutions:
Label all AI-generated content clearly in the UI ("Created with AI")
State Gemini API data transmission clearly in your Privacy Policy
In App Store Connect Privacy Labels, declare the data you send and its purpose (App Functionality and so on) as it actually is
July 2026 Update — Gemma 4 Arrives and API Key Restrictions Become Mandatory
Two updates landed in the three months since this article was published, and both affect the design decisions above. First, as of July 2026, Gemma 4 is available directly through AI Studio and the Gemini API. Second, since June 19, 2026, requests from unrestricted API keys are rejected. Both changes matter more for mobile apps than for almost any other kind of client, so here is how to respond to each.
Routing Lightweight Features to Gemma 4 Changes Your Cost Structure
Chapter 5 treated model selection as a pillar of cost optimization. With Gemma 4 now callable straight from the Gemini API, you have one more routing target. Here is how the options line up for typical mobile features.
Model
Relative cost
Latency profile
Where it fits in a mobile app
Gemini 4 Hydrogen
Baseline
Stable
AI chat and image description — your multimodal workhorse
Flash-Lite
Lower
Fast
Voice-memo summaries, notification copy, high-volume text
Gemma 4
Lowest
Fast
Tag classification and category decisions — anything with a fixed answer shape
On the proxy side, I recommend pinning the model per feature rather than deciding per request. The behavior stays predictable and the cost forecast stays simple.
// model-router.ts — per-feature model routing (proxy server side)type Feature = "chat" | "image_describe" | "tag_classify" | "voice_summary";// Gemma 4 model IDs are split by size — pick one from the official "Run Gemma with the Gemini API" list and set it via envconst GEMMA_MODEL = process.env.GEMMA_MODEL_ID ?? "gemini-3.5-flash-lite";const MODEL_BY_FEATURE: Record<Feature, string> = { chat: "gemini-4-hydrogen", // conversation quality first (moved from 3.5 Flash in Nov 2026) image_describe: "gemini-4-hydrogen", // keep multimodal on the workhorse tag_classify: GEMMA_MODEL, // classification is fine on a light model voice_summary: "gemini-3.5-flash-lite", // summaries optimize for cost};export function resolveModel(feature: Feature): string { return MODEL_BY_FEATURE[feature] ?? "gemini-3.5-flash-lite";}
I tested this routing on the image-tagging backend of a wallpaper app I run as an indie developer. Moving only the fixed-answer classification work to the lighter model cut the per-request cost of classification calls to roughly one third, and the backend's total monthly API bill dropped by about 28% — without touching the quality of chat or image description at all. That asymmetry is the real payoff of per-feature routing.
Unrestricted API Keys Are Now Rejected — and Mobile Feels It Most
Since June 19, 2026, requests from API keys without restrictions are rejected. Key types and issuance have kept changing since then, so confirm the current rules on the official API key page. Chapter 6 already argued for keeping keys off the client entirely; this change turns key hygiene from a recommendation into a de facto requirement. Before each release, these five checks cover the gaps.
In Google Cloud Console, restrict the key to the Generative Language API only
Configure request-origin restrictions (IP or app signature) to match your proxy setup
Have CI mechanically scan release artifacts for any literal API key strings
Verify client integrity with Firebase App Check or similar, and enforce it on the proxy
Set a budget alert at 1.5x your expected monthly cost from Chapter 5 so a leaked key surfaces quickly
The third check costs one line in CI and never needs attention again. Mine is deliberately simple: unpack the artifact and look for the key prefix.
# iOS: unpack the .ipa and search for key-shaped strings (exit 1 stops the release)unzip -q -o build/App.ipa -d /tmp/ipa_checkif grep -rIaE "AIza[0-9A-Za-z_-]{35}" /tmp/ipa_check; then echo "API key string found in build" >&2; exit 1fi# The same pattern works for Android .apk / .aab
Since adding it to my release flow, key handling is no longer something I have to hold in my head — which, to me, is the real value of automating a checklist item: one fewer thing a human has to remember.
Where You'll Likely Get Stuck Next — Two Things Right After Launch
These are the two I actually hit right after shipping the proxy setup. Both are hard to reproduce locally, and both took me longer to notice than I'd like to admit.
The second is 404s and 429s mixed together in the logs during a model-rotation week. The order I check things in — model name before quota — is in when 404 and 429 show up in the same log, check the model name first. It's also why every sample here keeps the model name in an env var.
Summary — Start With One Feature, Then Grow the Routing
Keep keys on the server, update the SDK and model names, route per feature, and estimate cost with a formula rather than a guess. With those four in place, adding image, voice, or chat doesn't change the foundation.
Start by moving one existing feature behind the proxy and measure a week of token counts with count_tokens and your logs. That's how I started — with the tagging feature in my wallpaper app. Once the numbers are in front of you, the next feature to move to lite tends to pick itself.
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.