Google Gemini 1.5 Pro & Flash API: Multimodal Prompting, Function Calling & Structured JSON with Node.js
Master Google Gemini 1.5 Pro and Flash in Node.js. Learn multimodal image & video inputs, native structured JSON outputs, system instructions, function calling, and token budgeting.

Google's Next-Generation Multimodal AI Engine#
Google's Gemini 1.5 family of models represents a major leap in generative AI capabilities for developers. Featuring an unprecedented 2-million-token context window, native multimodal architecture (processing text, audio, high-resolution images, and full video files simultaneously), and breakthrough inference speeds with Gemini 1.5 Flash, the Gemini API has become a premier choice for production software applications.
This tutorial provides a practical, code-level guide to integrating the Google Generative AI SDK in TypeScript and Node.js.
1. Setting Up the Google GenAI SDK#
Install the official Google Generative AI package:
npm install @google/generative-ai dotenvObtain your API key from [Google AI Studio](https://aistudio.google.com) and store it in your .env.local file:
GEMINI_API_KEY=your_actual_gemini_api_key_hereInitialize the client in TypeScript:
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
// Gemini 1.5 Flash: Ultra-fast, lightweight, highly cost-effective
export const flashModel = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
generationConfig: {
temperature: 0.2, // Low temperature for deterministic outputs
topP: 0.8,
maxOutputTokens: 2048,
},
});
// Gemini 1.5 Pro: Deep reasoning, complex coding, and massive document analysis
export const proModel = genAI.getGenerativeModel({
model: "gemini-1.5-pro",
});2. Multimodal Vision: Analyzing Images and Documents#
Unlike traditional models that rely on separate OCR pipelines, Gemini natively understands raw visual bytes:
import * as fs from "fs";
function fileToGenerativePart(path: string, mimeType: string) {
return {
inlineData: {
data: Buffer.from(fs.readFileSync(path)).toString("base64"),
mimeType,
},
};
}
export async function analyzeArchitectureDiagram(imagePath: string) {
const imagePart = fileToGenerativePart(imagePath, "image/png");
const prompt = `
Analyze this system architecture diagram.
1. Identify all database and caching nodes.
2. Point out potential single points of failure.
3. Suggest architectural resilience improvements.
`;
const result = await flashModel.generateContent([prompt, imagePart]);
return result.response.text();
}3. Enforcing Structured JSON Output#
In production backends, you need guaranteed, parseable JSON data conforming to strict schema definitions:
import { SchemaType } from "@google/generative-ai";
const structuredModel = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
generationConfig: {
responseMimeType: "application/json",
responseSchema: {
type: SchemaType.OBJECT,
properties: {
recipeName: { type: SchemaType.STRING },
prepTimeMinutes: { type: SchemaType.NUMBER },
ingredients: {
type: SchemaType.ARRAY,
items: { type: SchemaType.STRING },
},
difficulty: {
type: SchemaType.STRING,
enum: ["Easy", "Medium", "Hard"],
},
},
required: ["recipeName", "prepTimeMinutes", "ingredients", "difficulty"],
},
},
});
export async function generateStructuredRecipe(userPrompt: string) {
const result = await structuredModel.generateContent(userPrompt);
// Guaranteed valid JSON matching the schema!
const parsedData = JSON.parse(result.response.text());
return parsedData;
}4. Real-World Function Calling (Tools)#
Function calling allows Gemini to interface directly with your backend database, external REST APIs, or local calculation engines:
const databaseTool = {
functionDeclarations: [
{
name: "getUserSubscriptionStatus",
description: "Lookup a user's current billing tier and active credits",
parameters: {
type: SchemaType.OBJECT,
properties: {
userId: { type: SchemaType.STRING, description: "The unique customer ID" },
},
required: ["userId"],
},
},
],
};
const toolModel = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
tools: [databaseTool],
});
export async function handleCustomerInquiry(userMessage: string) {
const chat = toolModel.startChat();
const response = await chat.sendMessage(userMessage);
const functionCalls = response.response.functionCalls();
if (functionCalls && functionCalls.length > 0) {
const call = functionCalls[0];
console.log(`Gemini requested tool execution: ${call.name}`, call.args);
// Execute actual database query
const dbResult = { tier: "Enterprise", activeCredits: 4500 };
// Send function execution result back to Gemini
const finalResponse = await chat.sendMessage([
{
functionResponse: {
name: call.name,
response: dbResult,
},
},
]);
return finalResponse.response.text();
}
return response.response.text();
}5. Gemini Model Selection Matrix#
| Model Tier | Latency | Context Window | Best Use Case |
|---|---|---|---|
| Gemini 1.5 Flash | Ultra-Fast (~150ms TTFT) | 1,000,000 Tokens | High-frequency chat, customer support, real-time audio/video processing |
| Gemini 1.5 Pro | Moderate (~500ms TTFT) | 2,000,000 Tokens | Complex code generation, 1,000-page document analysis, multi-step math |
| Gemini Nano | Local Device Speed | On-Device RAM | Android on-device smart replies, local privacy-first tasks |
6. Frequently Asked Questions (FAQ)#
Q: What is the benefit of Gemini's 2-million-token context window? A 2-million context window allows you to upload entire code repositories (hundreds of TypeScript and Python files) or 2 hours of HD video directly in the prompt without needing complex RAG chunking pipelines.
Q: Is Gemini 1.5 Flash free to test? Yes. Google AI Studio provides generous free tier rate limits (up to 15 RPM for Gemini 1.5 Flash) for developers building and prototyping applications.

Published by
Vyuhantrix Team
AI Engineering · Vyuhantrix
Vyuhantrix is an open technology learning platform based in Ahmedabad, India, publishing step-by-step programming tutorials, system design breakdowns, and free developer tools.
Keep Learning
Recommended Guides
The Definitive Full-Stack Web Development Roadmap (2026 Edition)
A complete step-by-step masterclass covering modern HTML5/CSS, TypeScript, Next.js App Router, Server Components, API Design, and Cloud Edge Deployments.
Top 5 Programming Languages to Learn in 2026 for High-Impact Careers
Discover the most in-demand languages driving cloud infrastructure, AI development, web platforms, systems engineering, and enterprise backend systems.
OpenAI API Integration: Building Production AI Features in Node.js
A practical engineering guide to integrating OpenAI's GPT and Embeddings APIs into production Node.js applications — covering streaming responses, token management, error handling, rate limits, structured output, and cost optimization.