AI product engineering: building reliable AI features after the demo A practical handbook by Flavio for building reliable AI features in production with Google Gemini models, tested in live Node.js runs against the @google/genai v3.6.1 SDK using gemini-decision-1, gemini-4-hydrogen, gemini-4-neon, gemini-4-argon, and gemini-embedding-001. The guide covers when to skip AI for plain code, model selection, structured output, tool calling, hybrid RAG with pre-retrieval permission filters, evals and CI gates, guardrails, prompt injection, cost, caching, fallbacks, observability, human approval, workflows versus agents, and model migrations, using a fictional webhook relay called Hookline as its test case. Flavio reports the entire suite of experiments cost under $1, and notes Google AI Pro includes $10/month and Google AI Ultra $40/month (5x) or $100/month (20x) in Google Developer Program API credits valid for 12 months. AI product engineering: building reliable AI features after the demo By Flavio https://flaviocopes.com/about/ Tagged: AI https://flaviocopes.com/tags/ai/ A practical handbook for shipping AI inside real products with Google Gemini models: when to use AI, model selection, structured output, tool calling, hybrid RAG, evals, guardrails, prompt injection, cost, caching, fallbacks, observability, human approval, workflows vs agents, and model migrations. Using AI to write software and putting AI inside the software you ship are two different jobs. My AI Workshop https://flaviocopes.com/courses/ai-workshop/ teaches the first job: working with coding agents like Claude Code and Codex to plan, edit, and test your codebase. If an agent makes a bad edit there, you catch it in a diff before you commit. AI product engineering is the second job. You put a language model behind an API route, a button, or a background worker, and real users hit it while you are asleep. Nobody is reading every diff. Your code has to handle bad JSON, slow responses, runaway token bills, leaked API keys, prompt injections, and model upgrades on its own. A weekend demo takes twenty lines of code. Keeping that feature accurate, fast, safe, and affordable six months later is where the real engineering lives. Every benchmark, JSON response, hybrid search result, eval table, trace log, and terminal screenshot in this guide comes from live Node.js runs against Google’s Gemini API @google/genai v3.6.1 : gemini-decision-1 , gemini-4-hydrogen , gemini-4-neon , gemini-4-argon , and gemini-embedding-001 . A quick note on API costs if you have Google AI Pro or Ultra: your consumer subscription covers the Gemini app and Antigravity, not raw API traffic. API billing runs separately through Google Cloud. Before you pay out of pocket, open Google AI Studio https://aistudio.google.com/ with your subscribed account and look in the bottom-left sidebar for Redeem in API credits step-by-step walkthrough https://flaviocopes.com/google-ai-ultra-api-credits/ . Google AI Pro includes $10/month and Google AI Ultra includes $40/month 5x or $100/month 20x in Google Developer Program credits that stay valid for 12 months and spend down before your card is charged. The entire suite of experiments in this guide cost under $1. The teaching thread Every concept in this guide stands on its own. To test real code instead of inventing fake numbers, I ran every pattern against one small, neutral example: a bug-report triage and docs-search backend for a fictional webhook relay called Hookline . Incoming bug reports are messy. Users paste broken stack traces, write in different languages, exaggerate feature requests as “P0 outages”, accidentally include live API keys, report real security vulnerabilities like SSRF, and sometimes hide prompt injections inside HTML comments. Behind the scenes, Hookline has 10 public docs and 2 confidential unpatched security advisories SEC-2026-04 and SEC-2026-07 that public users must never see. That tiny surface exercises every real problem you hit when putting AI into a product. Find your way around this guide This is a long handbook, so jump straight to the topic you need: | Topic | Jump to | |---|---| | Decide when to skip AI and write plain code | Choosing when AI is appropriate choosing-when-ai-is-appropriate | | Compare models, thinking levels, latency, and real cost | Model selection model-selection | | Enforce schemas, Zod rules, and the maxOutputTokens trap | Structured output structured-output | | Design safe, narrow, validated tool calls | Tool calling tool-calling | | Version prompts, design context, and handle abstention | Prompt and context design prompt-and-context-design | | Build hybrid search with pre-retrieval permission filters | Retrieval and search retrieval-and-search | | Replace vibe-checking with golden datasets and CI gates | Evals evals | | Scrub secrets, verify citations, and guard inputs and outputs | Guardrails guardrails | | Defend against direct and indirect prompt injection in code | Prompt-injection risk prompt-injection-risk | | Control thinking tokens, p95 latency, and monthly spend | Cost and latency cost-and-latency | | Use provider prefix caching, exact caching, and semantic caching | Caching caching | | Handle 429s, timeouts, fallbacks, and graceful degradation | Fallbacks fallbacks | | Emit structured traces and build the eval flywheel | Observability observability | | Build payload-bound human approval for irreversible actions | Human approval human-approval | | Choose deterministic workflows over open-ended agent loops | Agents versus deterministic workflows agents-versus-deterministic-workflows | | Isolate your app from model deprecations and provider swaps | Handling model and provider changes handling-model-and-provider-changes | | Put everything together before launch | How I would build an AI feature today how-i-would-build-an-ai-feature-today | If tokens, embeddings, or context windows are new to you, read my AI fundamentals guide https://flaviocopes.com/ai-fundamentals/ or check the AI glossary https://flaviocopes.com/ai-glossary/ first. Choosing when AI is appropriate The fastest way to ship a bad AI feature is to use a language model for a job that ten lines of deterministic code already solve better. LLMs are probabilistic text engines. They are great at messy inputs that resist rigid rules: free-form user messages, logs in arbitrary formats, cross-lingual text, and matching prose questions against prose documentation. They are terrible at exact arithmetic, strict access control, version comparisons, and anything where a 1% silent error rate is unacceptable without verification. Use this table before you write your first prompt: | Job | Best tool | Why | |---|---|---| | Check if SDK v2.0.4 is end-of-life < 2.1.0 | Plain semver code | 100% accurate, 0.01 ms, $0 | | Redact leaked hl live ... API keys from user text | Regex before the API call | Never send raw secrets to a third-party model | | Check if a user can read internal advisory SEC-2026-04 | SQL WHERE visibility = 'public' | Access control belongs in your database, not a prompt | | Route an issue by security risk, component, and priority | Typed classifier gemini-decision-1 | 386 ms, 0 output tokens, $0.04 per 1,000 calls | | Extract repro steps and draft a grounded reply from docs | Generative model gemini-4-hydrogen | Handles messy English, Italian, stack traces, and prose | | Issue a $1,500 bug bounty payout | Human approval + idempotent code | Money movement must never depend on a probabilistic call | In Hookline, the model extracts affected version: "2.0.4" from a rambling bug report. Plain JavaScript then checks whether that version is end-of-life: js export function compareSemver a, b { const pa = a.replace /^v/, '' .split '.' .map Number const pb = b.replace /^v/, '' .split '.' .map Number for let i = 0; i < 3; i++ { if pa i ?? 0 == pb i ?? 0 return pa i ?? 0 - pb i ?? 0 } return 0 } const isEndOfLife = compareSemver '2.0.4', '2.1.0' < 0 // true Split every AI feature along that seam. Put the model on ambiguity and language. Put deterministic code on math, policy thresholds, permissions, and side effects. Model selection Picking a model by reading a marketing benchmark or looking at list prices per million tokens will burn you in production. Two numbers decide whether a model fits a product feature: real end-to-end latency and real cost per completed task , including thinking tokens. Google’s current API lineup gives us four distinct tiers AI model names explained https://flaviocopes.com/ai-model-names/ : | Model | API ID | List price in / out per 1M | Role in a product | |---|---|---|---| | Gemini Decision 1 | gemini-decision-1 | $0.10 / $0.00 | Fast routing, yes/no gates, classification, scoring 0 output tokens | | Gemini 4 Hydrogen | gemini-4-hydrogen | $1.50 / $7.50 | High-volume extraction, tool calling, everyday generation | | Gemini 4 Neon | gemini-4-neon | $3.00 / $15.00 | Deep reasoning, hard synthesis, long-context analysis | | Gemini 4 Argon | gemini-4-argon | $2.00 / $10.00 $4 / $20 after Nov 30 | High-accuracy reasoning with lower thinking-token overhead | To see how they actually behave, I ran the same 6 tricky Hookline bug reports signature mismatch, SSRF redirect, hyped feature request, leaked secret, vague one-liner, and old-version memory leak through every tier and thinking level, with maxOutputTokens: 1024 : | Model and setting | Accuracy | Valid schema | Avg latency | Avg input tok | Avg thought tok | Avg output tok | Cost / 1,000 calls | |---|---|---|---|---|---|---|---| | gemini-decision-1 Decisions API | 4/6 | 6/6 | 386 ms | 381 | 0 | 0 | $0.04 | | gemini-4-hydrogen low | 3/6 | 6/6 | 3,813 ms | 1,029 | 336 | 166 | $5.31 | | gemini-4-hydrogen high | 4/6 | 6/6 | 5,444 ms | 1,029 | 507 | 182 | $6.70 | | gemini-4-neon low | 4/6 | 6/6 | 12,260 ms | 1,032 | 429 | 182 | $12.26 | | gemini-4-neon high | 1/6 | 2/6 | 17,100 ms | 1,032 | 837 | 87 | $16.96 | | gemini-4-argon low | 4/6 | 6/6 | 8,165 ms | 1,029 | 0 | 176 | $3.82 | Three production lessons jump straight out of those real numbers: 1. List price lies about real cost. gemini-4-argon lists at $2 / $10, more expensive per token than gemini-4-hydrogen at $1.50 / $7.50. Yet Argon cost $3.82 per 1,000 calls while Hydrogen cost $5.31 , because Argon used 0 thinking tokens at low while Hydrogen spent 336 thinking tokens billed at the output rate. I saw the exact same pattern with Neon’s thinking habits in my Gemini 4 Neon review https://flaviocopes.com/gemini-4-neon-review/ . 2. Routing beats using one model for everything. gemini-decision-1 answered in 386 ms for $0.04 per 1,000 calls . That is 10x faster and 133x cheaper than gemini-4-hydrogen , and 32x faster and 306x cheaper than gemini-4-neon . When a task only needs routing, spam checks, or confidence scores, use the Gemini Decisions API https://flaviocopes.com/gemini-decisions-api/ first and only wake a generative model when you actually need prose or extraction. 3. Never drop a heavy reasoning model into a synchronous UI without measuring p95 latency. On a single cold "Say ok" probe, gemini-4-neon took 38.3 seconds, and it averaged 12.2 seconds on triage at low . That is fine for an asynchronous background job. In a user-facing search box or checkout flow, it feels broken. And notice row 5 gemini-4-neon at high : only 2/6 responses parsed as valid JSON. That brings us directly to structured output. Structured output If your app parses model output into database rows, UI badges, or downstream API calls, asking for “valid JSON” inside your prompt will break in production. Here is what gemini-4-hydrogen returned when I asked it in plain text to extract fields as JSON from the v2.0.4 memory-leak report: json { "component": "@hookline/sdk", "severity": "high", "affected version": "2.0.4", "is security issue": false } Two things broke immediately. First, it wrapped the JSON in markdown fences, so JSON.parse throws. Second, it returned "@hookline/sdk" instead of the enum value "sdk" our database expects. Fix this in three layers: 1. Constrained decoding at the API layer. Pass responseMimeType: 'application/json' and responseJsonSchema . The model runtime restricts token sampling to bytes that match your JSON Schema. 2. Runtime validation in your code with Zod. Treat model JSON like any untrusted HTTP request body. Validate regex patterns bare semver ^\d+\.\d+\.\d+$ , string lengths, and enums. 3. Deterministic domain checks. Verify invariants a JSON Schema cannot express: cited doc IDs must exist in the docs you actually retrieved, totals must equal the sum of line items, and semver versions get checked by code. Here is the exact constrained call with @google/genai and Zod: js import { GoogleGenAI, ThinkingLevel } from '@google/genai' import { z } from 'zod' const TriageSchema = z.object { component: z.enum 'delivery', 'security', 'api', 'sdk', 'cli' , severity: z.enum 'low', 'medium', 'high', 'critical' , is security issue: z.boolean , affected version: z.string .regex /^\d+\.\d+\.\d+$/ .nullable , needs maintainer: z.boolean , cited doc ids: z.array z.string , summary: z.string .min 10 .max 240 , suggested reply: z.string .min 10 .max 600 , } const ai = new GoogleGenAI const res = await ai.models.generateContent { model: 'gemini-4-hydrogen', contents: issuePrompt, config: { systemInstruction: PROMPT V2, responseMimeType: 'application/json', responseJsonSchema: TRIAGE JSON SCHEMA, thinkingConfig: { thinkingLevel: ThinkingLevel.LOW }, maxOutputTokens: 2048, }, } const triage = TriageSchema.parse JSON.parse res.text With constrained decoding enabled, the exact same bug report produced clean, fence-free JSON: { "component": "sdk", "severity": "high", "is security issue": false, "affected version": "2.0.4", "needs maintainer": false, "cited doc ids": "doc-v3-migration" , "summary": "Memory leak leading to OOM in @hookline/sdk v2.0.4 when downstream servers return chunked 502 responses.", "suggested reply": "This memory leak in the HTTP keep-alive pool on chunked 502 responses was fixed in @hookline/sdk v2.1.0. Versions below v2.1.0 are end-of-life, so please upgrade to v2.1.0 or later or v3.0.0+, which supports Node 20+ ." } Watch out for the maxOutputTokens thinking trap Look back at why gemini-4-neon at high failed 4 of 6 schema checks in our benchmark. In Gemini, maxOutputTokens caps thinking tokens plus visible output tokens combined . We set maxOutputTokens: 1024 . At high thinking, Neon spent an average of 837 thinking tokens before it started writing JSON, leaving fewer than 190 tokens for the entire JSON object. The API cut the stream mid-string and JSON.parse failed. When I re-ran gemini-4-neon at high with maxOutputTokens: 4096 , it spent 637 thinking tokens and 23 output tokens and returned valid JSON cleanly. When you use any reasoning model with structured output, size maxOutputTokens to hold the worst-case thinking budget plus the schema payload, and inspect finishReason MAX TOKENS vs STOP before parsing. If Zod fails on a semantic rule like returning "v2.0.4" instead of "2.0.4" , run at most one bounded repair retry passing the exact validation error back, then fall back to a human queue. Tool calling Tool calling lets a model ask your application to run a function and return live data. The model never executes code directly. It returns a structured functionCalls array, your code validates the arguments and runs the function, and you send the result back as a functionResponse part. Here is a minimal read-only tool loop with @google/genai : js const tools = { functionDeclarations: { name: 'check version eol', description: 'Check whether a Hookline SDK semver is end-of-life < 2.1.0 .', parametersJsonSchema: { type: 'object', properties: { version: { type: 'string', description: 'Bare semver like 2.0.4' }, }, required: 'version' , }, }, , }, const res = await ai.models.generateContent { model: 'gemini-4-hydrogen', contents, config: { systemInstruction: 'Use tools to check version EOL status, then summarize.', tools, thinkingConfig: { thinkingLevel: ThinkingLevel.LOW }, }, } for const call of res.functionCalls ?? { if call.name === 'check version eol' { const version = String call.args?.version ?? '' const isEol = /^\d+\.\d+\.\d+$/.test version ? compareSemver version, '2.1.0' < 0 : null contents.push res.candidates 0 .content contents.push { role: 'user', parts: { functionResponse: { name: call.name, response: { version, isEol } } } , } } } Five rules separate reliable product tools from fragile demos: - Validate every argument in code. Schema constraints make malformed arguments rarer, not impossible. Check regexes, IDs, and permissions before touching a database or external API. - Keep tools narrow and purpose-built. Give the model search public docs query and add label label enum , not run sql query or github api method, path, body . - Split read tools from write tools. Never register a money-moving or data-deleting tool in the same request that reads untrusted external text. - Truncate and paginate tool results. If a search tool dumps 80 KB of raw logs into functionResponse , you burn context, spike latency, and drown out your instructions. Return only the top 3 snippets and the fields the model needs. - Make write tools idempotent. Models retry on timeouts and duplicate calls happen. Require an idempotency key so the same write cannot execute twice. If you want to expose tools across several apps or clients over a standard protocol, see my guide on building an MCP server https://flaviocopes.com/build-mcp-server/ . Prompt and context design A prompt in a production product is code. Treat it like code. Keep prompts in dedicated versioned modules PROMPT V1 , PROMPT V2 with explicit version IDs logged on every request. Never concatenate prompt fragments inside route handlers where you cannot diff them or link a quality drop to a commit. Structure every context window deliberately: 1. Static instructions and rubric first. Put your system prompt, schema rules, and examples at the very top so every request shares an identical prefix. 2. Retrieved facts next, clearly fenced. Wrap ground-truth docs in